android上傳大文件親測可用,上傳200M個文件,不到3分鍾
之前貼過個例子是android 入門學習筆記 上傳大文件 這種的文件大小限製很嚴,一般30M以上就報錯了。網上查了一下,還是推薦用Socket連接進行大文件上傳。
今天測試了一下之前網上找的例子,通過Socket實現的android下大文件上傳,服務器端用java接收。測試上傳了個200M的文件,不到三分鍾!還是可以接受的。
隻是做了個簡單的測試例子,還沒有考慮到權限問題(手機上傳資料到服務器端,應該需要做身份驗證。。)
- connection.setChunkedStreamingMode(chunkSize);
使用這個代碼就可以了,connection為 HttpURLConnection的實例
完整代碼如下:
- /* 上傳文件至Server的方法 */
- private void uploadFile()
- {
- String end = "\r\n";
- String twoHyphens = "--";
- String boundary = "*****";
- try
- {
- URL url =new URL(actionUrl);
- HttpURLConnection con=(HttpURLConnection)url.openConnection();
- con.setChunkedStreamingMode(51200);
- /* 允許Input、Output,不使用Cache */
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
- /* 設置傳送的method=POST */
- con.setRequestMethod("POST");
- /* setRequestProperty */
- con.setRequestProperty("Connection", "Keep-Alive");
- con.setRequestProperty("Charset", "UTF-8");
- con.setRequestProperty("Content-Type",
- "multipart/form-data;boundary="+boundary);
- /* 設置DataOutputStream */
- DataOutputStream ds =
- new DataOutputStream(con.getOutputStream());
- ds.writeBytes(twoHyphens + boundary + end);
- ds.writeBytes("Content-Disposition: form-data; " +
- "name=\"file1\";filename=\"" +
- newName +"\"" + end);
- ds.writeBytes(end);
- /* 取得文件的FileInputStream */
- FileInputStream fStream = new FileInputStream(uploadFile);
- /* 設置每次寫入1024bytes */
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
- int length = -1;
- /* 從文件讀取數據至緩衝區 */
- while((length = fStream.read(buffer)) != -1)
- {
- /* 將資料寫入DataOutputStream中 */
- ds.write(buffer, 0, length);
- }
- ds.writeBytes(end);
- ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
- /* close streams */
- fStream.close();
- ds.flush();
- /* 取得Response內容 */
- InputStream is = con.getInputStream();
- int ch;
- StringBuffer b =new StringBuffer();
- while( ( ch = is.read() ) != -1 )
- {
- b.append( (char)ch );
- }
- /* 將Response顯示於Dialog */
- showDialog(b.toString().trim());
- /* 關閉DataOutputStream */
- ds.close();
- }
- catch(Exception e)
- {
- showDialog(""+e);
- }
- }
應要求貼上源碼下載地址:https://download.csdn.net/detail/jdsjlzx/8150031
最後更新:2017-04-04 07:03:55