Bootstrap

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";
    }

 

;