http協議上傳檔案一般最大是2M,比較適合上傳小於兩M的檔案 [代碼] [Java]代碼 001import java.io.File; 002import java.io.FileInputStream; 003import java.io.FileNotFoundException; 004import java.io.InputStream; 005006/**007* 上傳的檔案008*/ 009public class FormFile { 010/** 上傳檔案的資料 */ 011private byte[] data; 012private InputStream inStream; 013private File file; 014/** 檔案名稱 */ 015private String filname; 016/** 請求參數名稱*/ 017private String parameterName; 018/** 內容類型 */ 019private String contentType = "application/octet-stream"; 020/**021*022* @param filname 檔案名稱023* @param data 上傳的檔案資料024* @param parameterName 參數025* @param contentType 內容類型026*/ 027public FormFile(String filname, byte[] data, String parameterName, String contentType) { 028this.data = data; 029this.filname = filname; 030this.parameterName = parameterName; 031if(contentType!=null) this.contentType = contentType; 032}033/**034*035* @param filname 檔案名稱036* @param file 上傳的檔案037* @param parameterName 參數038* @param contentType 內容內容類型039*/ 040public FormFile(String filname, File file, String parameterName, String contentType) { 041this.filname = filname; 042this.parameterName = parameterName; 043this.file = file; 044try { 045this.inStream = new FileInputStream(file); 046} catch (FileNotFoundException e) { 047e.printStackTrace();048}049if(contentType!=null) this.contentType = contentType; 050}051052public File getFile() { 053return file; 054}055056public InputStream getInStream() { 057return inStream; 058}059060public byte[] getData() { 061return data; 062}063064public String getFilname() { 065return filname; 066}067068public void setFilname(String filname) { 069this.filname = filname; 070}071072public String getParameterName() { 073return parameterName; 074}075076public void setParameterName(String parameterName) { 077this.parameterName = parameterName; 078}079080public String getContentType() { 081return contentType; 082}083084public void setContentType(String contentType) { 085this.contentType = contentType; 086}087088}089090/**091* 直接通過HTTP協議提交資料到伺服器,實現如下面表單提交功能:092* <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data">093<INPUT TYPE="text" NAME="name">094<INPUT TYPE="text" NAME="id">095<input type="file" name="imagefile"/>096<input type="file" name="zip"/>097</FORM>098* @param path 上傳路徑(註:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080這樣的路徑測試)099* @param params 請求參數 key為參數名,value為參數值100* @param file 上傳檔案101*/ 102public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{ 103final String BOUNDARY = "---------------------------7da2137580612"; //資料分隔線 104final String endline = "--" + BOUNDARY + "--\r\n";//資料結束標誌 105106int fileDataLength = 0; 107for(FormFile uploadFile : files){//得到檔案類型資料的總長度 108StringBuilder fileExplain = new StringBuilder(); 109fileExplain.append("--"); 110fileExplain.append(BOUNDARY);111fileExplain.append("\r\n");112fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");113fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"); 114fileExplain.append("\r\n");115fileDataLength += fileExplain.length(); 116if(uploadFile.getInStream()!=null){ 117fileDataLength += uploadFile.getFile().length(); 118}else{119fileDataLength += uploadFile.getData().length; 120}121}122StringBuilder textEntity = new StringBuilder(); 123for (Map.Entry<String, String> entry : params.entrySet()) {//構造文本型別參數的實體資料 124textEntity.append("--"); 125textEntity.append(BOUNDARY);126textEntity.append("\r\n");127textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n"); 128textEntity.append(entry.getValue());129textEntity.append("\r\n");130}131//計算傳輸給伺服器的實體資料總長度 132int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length; 133134URL url = new URL(path); 135int port = url.getPort()==-1 ? 80 : url.getPort(); 136Socket socket = new Socket(InetAddress.getByName(url.getHost()), port); 137OutputStream outStream = socket.getOutputStream(); 138//下面完成HTTP要求標頭的發送 139String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n"; 140outStream.write(requestmethod.getBytes());141String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";142outStream.write(accept.getBytes());143String language = "Accept-Language: zh-CN\r\n"; 144outStream.write(language.getBytes());145String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n"; 146outStream.write(contenttype.getBytes());147String contentlength = "Content-Length: "+ dataLength + "\r\n"; 148outStream.write(contentlength.getBytes());149String alive = "Connection: Keep-Alive\r\n"; 150outStream.write(alive.getBytes());151String host = "Host: "+ url.getHost() +":"+ port +"\r\n"; 152outStream.write(host.getBytes());153//寫完HTTP要求標頭後根據HTTP協議再寫一個斷行符號換行 154outStream.write("\r\n".getBytes());155//把所有文本類型的實體資料發送出來 156outStream.write(textEntity.toString().getBytes());157//把所有檔案類型的實體資料發送出來 158for(FormFile uploadFile : files){ 159StringBuilder fileEntity = new StringBuilder(); 160fileEntity.append("--"); 161fileEntity.append(BOUNDARY);162fileEntity.append("\r\n");163fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");164fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"); 165outStream.write(fileEntity.toString().getBytes());166if(uploadFile.getInStream()!=null){ 167byte[] buffer = new byte[1024]; 168int len = 0; 169while((len = uploadFile.getInStream().read(buffer, 0,1024))!=-1){ 170outStream.write(buffer, 0, len); 171}172uploadFile.getInStream().close();173}else{174outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); 175}176outStream.write("\r\n".getBytes());177}178//下面發送資料結束標誌,表示資料已經結束 179outStream.write(endline.getBytes());180181BufferedReader reader = new BufferedReader(newInputStreamReader(socket.getInputStream())); 182if(reader.readLine().indexOf("200")==-1){//讀取web伺服器返回的資料,判斷請求碼是否為200,如果不是200,代表請求失敗183return false; 184}185outStream.flush();186outStream.close();187reader.close();188socket.close();189return true; 190}191192/**193* 提交資料到伺服器 194* @param path 上傳路徑(註:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080這樣的路徑測試)195* @param params 請求參數 key為參數名,value為參數值 196* @param file 上傳檔案 197*/ 198public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{ 199return post(path, params, new FormFile[]{file}); 200}