Java通過HTTP方式傳輸文件

最近再做項目的過程中又遇到通過HTTP方式上傳文件的需求,想起來之前有實現過這個功能,只是時間太長不記得了,擔心下次再忘於是就有了下面這篇文章。

先貼段客戶端這邊的代碼吧

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

import com.dianping.cat.Cat;

public class FileLoadClient {
	
	private static final int TIMEOUT = 5000;
	
	public static String fileload(String url, File file) {
        String body = "{}";
        
        if (url == null || url.equals("")) {
            return "illegal";
        }
        if (!file.exists()) {
            return "file not exist";
        }
        
        PostMethod postMethod = new PostMethod(url);
        BufferedReader br = null;
        try {            
            // FilePart:用來上傳文件的類,file即要上傳的文件
            FilePart fp = new FilePart("file", file);
            Part[] parts = { fp };

            // 對於MIME類型的請求,httpclient建議全用MulitPartRequestEntity進行包裝
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            
            HttpClient client = new HttpClient();
            // 由於要上傳的文件可能比較大 , 因此在此設置最大的連接超時時間
            client.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT);
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                br = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }                
                body = stringBuffer.toString();                
            } else {
                body = "fail";
            }
        } catch (Exception e) {
            Cat.logError(e);
        } finally {
        	if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					Cat.logError(e);
				}
            // 釋放連接
            postMethod.releaseConnection();
        }        
        return body;
    }    
}

服務器端接收文件的代碼如下:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFile(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            try {
                String filePath = file.getOriginalFilename();
                InputStream inputStream = null;
                FileOutputStream outputStream = null;
                try {
                    inputStream = file.getInputStream();
                    File f = new File(filePath);
                    f.createNewFile();
                    byte[] bom = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
                    outputStream = new FileOutputStream(f);
                    if (filePath.endsWith(".txt")) {
                        outputStream.write(bom);//寫入BOM頭
                    }
                    byte temp[] = new byte[1024];
                    int size = -1;
                    while ((size = inputStream.read(temp)) != -1) { // 每次讀取1KB,直至讀完
                        outputStream.write(temp, 0, size);
                    }
                    response.getWriter().write("upload success");
                } catch (IOException e) {
                    return e.getMessage();
                } finally {
                    outputStream.close();
                    inputStream.close();
                }
            } catch (Exception e) {
                return e.getMessage();
            }
        }
        return "File is Empty";
    }

 

發佈了50 篇原創文章 · 獲贊 48 · 訪問量 45萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章