Android要實現文件上傳,能夠利用Socket上傳,也能夠模擬Web進行上傳,可是若是是使用第一種方式上傳,嚴格的話就得使用TCP,這樣容易生成系統死掉,或者是長時間等待,若是是UDP來傳,就容易形成數據丟失,所以在這裏選擇了Web進行上傳,使用Web進行上傳是模擬的Http Post上傳數據,固然,Post上傳數據的類,在網上找了一找,方式雖然不少,可是沒有一個感受是我所使用的,因此參照原理之類的,進行了一下修改,算是作了一個參考。而且利用這個類完成了文件和表彰的上傳服務。php
上傳方法一:java
public void uploadFile(){ String name=URLEncoder.encode(text1.getText().toString(),"utf-8"); String pass=URLEncoder.encode(text2.getText().toString(),"utf-8"); Map<String, String> params = new HashMap<String, String>(); params.put("NAME", name); params.put("PASSWORD", pass); post("http://192.168.1.120/dev/index.php/Device/UploadFile?filename=111&filetype=IMAGE", params, upfiles); } Map<String, File> upfiles = new HashMap<String, File>(); void getFile() { File file = new File("/sdcard/"); File[] files = file.listFiles(new fileFilter()); for (File f: files) { upfiles.put(f.getName(), new File("/sdcard/"+f.getName())); } // Toast.makeText(this, filename, Toast.LENGTH_LONG).show(); } class fileFilter implements FilenameFilter { @Override public boolean accept(File dir, String filename) { return filename.endsWith(".mp3"); } } // 上傳代碼,第一個參數,爲要使用的URL,第二個參數,爲表單內容,第三個參數爲要上傳的文件,能夠上傳多個文件,這根據須要頁定 public static boolean post(String actionUrl,Map<String, String> params,Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(5 * 1000); conn.setDoInput(true);// 容許輸入 conn.setDoOutput(true);// 容許輸出 conn.setUseCaches(false); conn.setRequestMethod("POST"); // Post方式 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先組拼文本類型的參數 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 發送文件數據 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: multipart/form-data; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // 請求結束標誌 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 獲得響應碼 boolean success = conn.getResponseCode()==200; InputStream in = conn.getInputStream(); InputStreamReader isReader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(isReader); String line = null; String data = "getResult="; while ((line = bufReader.readLine()) != null) data += line; outStream.close(); conn.disconnect(); return success; }
上傳方法二:數組
final String ENCORDING="UTF-8"; public boolean upload(String filepath) throws Exception { String boundary = "---------------------------7db1c523809b2";//+java.util.UUID.randomUUID().toString();// // 分割線 File file = new File(filepath); String fileName=new String("哈哈嗨".getBytes(),"ISO-8859-1"); // 用來解析主機名和端口 URL url = new URL("http://192.168.1.120/dev/index.php/Device/UploadFile?filename="+fileName+"&filetype=IMAGE"); // 用來開啓鏈接 StringBuilder sb = new StringBuilder(); // 用來拼裝請求 /*// username字段 sb.append("--" + boundary + "\r\n"); sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n"); sb.append("\r\n"); sb.append(username + "\r\n"); // password字段 sb.append("--" + boundary + "\r\n"); sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n"); sb.append("\r\n"); sb.append(password + "\r\n");*/ // 文件部分 sb.append("--" + boundary + "\r\n"); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + "\r\n"); sb.append("Content-Type: application/octet-stream" + "\r\n"); sb.append("\r\n"); // 將開頭和結尾部分轉爲字節數組,由於設置Content-Type時長度是字節長度 byte[] before = sb.toString().getBytes(ENCORDING); byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes(ENCORDING); // 打開鏈接, 設置請求頭 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(10000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + ""); conn.setDoOutput(true); conn.setDoInput(true); // 獲取輸入輸出流 OutputStream out = conn.getOutputStream(); FileInputStream fis = new FileInputStream(file); // 將開頭部分寫出 out.write(before); // 寫出文件數據 byte[] buf = new byte[1024*5]; int len; while ((len = fis.read(buf)) != -1) out.write(buf, 0, len); // 將結尾部分寫出 out.write(after); InputStream in = conn.getInputStream(); InputStreamReader isReader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(isReader); String line = null; String data = "getResult="; while ((line = bufReader.readLine()) != null) data += line; Log.e("fromServer", "result="+data); boolean sucess=conn.getResponseCode() == 200; in.close(); fis.close(); out.close(); conn.disconnect(); return sucess; }
經過此代碼就能夠實現將內容保存到SD卡等設備上,固然要使用網絡,必須得有網絡的訪問權限。這個須要本身添加,在這裏再也不添加!網絡