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包html

httpclient-4.2.jar前端

httpclient-cache-4.2.jarjava

httpcore-4.2.jarapache

httpmime-4.2.jar服務器

commons-logging-1.1.1.jarsession

相關文章
相關標籤/搜索