SpringMVC 利用HttpPost向服务端接口上传文件

现在Spring的广泛使用使得以前我们在做文件上传的不需要对数据进行转码传输,MultipartEntity内封装了各种方法,我们可以直接在客户端实例化
MultipartEntity类将需要上传的文件以参数的形式写入HttpPost的Entity,这样类似与在前端使用form表单提交来实现文件上传,区别是前端我们是在form里面设定enctype="multipart/form-data"这个参数。废话不多说,下面是代码;
 
首先是客户端:
import java.io.File;  
import java.io.IOException;  
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.HttpStatus;  
import org.apache.http.ParseException;  
import org.apache.http.client.HttpClient;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.mime.MultipartEntity;  
import org.apache.http.entity.mime.content.FileBody;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.util.EntityUtils; 


public class FileUploadClient {

    public void SubmitPost(String url, String file36Path, String file48Path, String file72Path,
            String file96Path, String file144Path) {

        HttpClient httpclient = new DefaultHttpClient();

        try {

            HttpPost httppost = new HttpPost(url);

            FileBody file36 = new FileBody(new File(file36Path));
            FileBody file48 = new FileBody(new File(file48Path));
            FileBody file72 = new FileBody(new File(file72Path));
            FileBody file96 = new FileBody(new File(file96Path));
            FileBody file144 = new FileBody(new File(file144Path));

            MultipartEntity reqEntity = new MultipartEntity();

            reqEntity.addPart("file36", file36);// file36为请求后台的File upload;属性
            reqEntity.addPart("file48", file48);
            reqEntity.addPart("file72", file72);
            reqEntity.addPart("file96", file96);
            reqEntity.addPart("file144", file144);
            
            httppost.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(httppost);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {

                System.out.println("服务器正常响应.....");

                HttpEntity resEntity = response.getEntity();

                System.out.println(EntityUtils.toString(resEntity));// httpclient自带的工具类读取返回数据

                System.out.println(resEntity.getContent());//这里是服务端的返回值

                EntityUtils.consume(resEntity);
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {

            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        FileUploadClient fileUploadClient = new FileUploadClient();

        fileUploadClient.SubmitPost(
                "http://127.0.0.1:8080/testProject/pictureUploadInterface.htm",
                "C://app_icon1.png", "C://app_icon2.png", "C://app_icon3.png", "C://app_icon4.png", "C://app_icon5.png");
    }

}
 
至于服务端,和Spring实现的一样
 
  /**
     * 图片上传接口
     * 
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/pictureUploadInterface", method = RequestMethod.POST)
    public String pictureUploadInterface(HttpServletRequest request,
            HttpServletResponse response, HttpSession session,
            @RequestParam("file36") MultipartFile file36,
            @RequestParam("file48") MultipartFile file48,
            @RequestParam("file72") MultipartFile file72,
            @RequestParam("file96") MultipartFile file96,
            @RequestParam("file144") MultipartFile file144)
            throws IOException {
        String filePath = "D://test";

        // 响应客户端  
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter();
        if (file36.isEmpty() && file48.isEmpty()
                && file72.isEmpty() && file96.isEmpty() && file144.isEmpty()) {
            out.write(-102);//-102 上传的图片全部为空
            return null;
        }
        if((game==null||game.equals(""))||(channel==null)||channel.equals("")){
            out.write(-100);//-100 参数错误
            return null;
        }
        
        if (!file36.isEmpty()) {
            if (!FilenameUtils.getExtension(file36.getOriginalFilename())
                    .equalsIgnoreCase("png")) {
                out.write(-101);//-101 图片格式错误
                return null;
            } else {
                String path = filePath + File.separator + "drawable-ldpi"
                        + File.separator + "app_icon.png";
                byte[] file36Byte = file36.getBytes();
                FileUtils.writeByteArrayToFile(new File(path), file36Byte);
                out.write(200);
            }
        }
        if (!file48.isEmpty()) {
            if (!FilenameUtils.getExtension(file48.getOriginalFilename())
                    .equalsIgnoreCase("png")) {
                out.write(-101);
                return null;
            } else {
                String path = filePath + File.separator + "drawable"
                        + File.separator + "app_icon.png";
                byte[] file48Bype = file48.getBytes();
                FileUtils.writeByteArrayToFile(new File(path), file48Bype);
            }
        }
        if (!file72.isEmpty()) {
            if (!FilenameUtils.getExtension(file72.getOriginalFilename())
                    .equalsIgnoreCase("png")) {
                out.write(-101);
                return null;
            } else {
                String path = filePath + File.separator + "drawable-hdpi"
                        + File.separator + "app_icon.png";
                byte[] file72Byte = file72.getBytes();
                FileUtils.writeByteArrayToFile(new File(path), file72Byte);
            }
        }
        if (!file96.isEmpty()) {
            if (!FilenameUtils.getExtension(file96.getOriginalFilename())
                    .equalsIgnoreCase("png")) {
                out.write(-101);
                return null;
            } else {
                String path = filePath + File.separator + "drawable-xhdpi"
                        + File.separator + "app_icon.png";
                byte[] file96Byte = file96.getBytes();
                FileUtils.writeByteArrayToFile(new File(path), file96Byte);
            }
        }
        if (!file144.isEmpty()) {
            if (!FilenameUtils.getExtension(file144.getOriginalFilename())
                    .equalsIgnoreCase("png")) {
                out.write(-101);
                return null;
            } else {
                String path = filePath + File.separator + "drawable-xxhdpi"
                        + File.separator + "app_icon.png";
                byte[] file144Byte = file144.getBytes();
                FileUtils.writeByteArrayToFile(new File(path), file144Byte);
            }
        }
        out.write(200);//200 上传图片成功
        out.close();
        return null;
    }


这里需要的JDR包

httpclient-4.2.jar

httpclient-cache-4.2.jar

httpcore-4.2.jar

httpmime-4.2.jar

commons-logging-1.1.1.jar

posted @ 2016-01-14 10:40  Acandy  阅读(8686)  评论(0编辑  收藏  举报