天天看點

Java 處理 multipart/mixed 請求

一、multipart/mixed 請求

  multipart/mixed 和 multipart/form-date 都是多檔案上傳的格式。差別在于:multipart/form-data 是一種特殊的表單上傳,其中普通字段的内容還是按照一般的請求體建構,檔案字段的内容按照 multipart 請求體建構,後端在處理 multipart/form-data 請求的時候,會在伺服器上建立臨時的檔案夾存放檔案内容,可參看這篇文章;而 multipart/mixed 請求會将每個字段的内容,不管是普通字段還是檔案字段,都變成 Stream 流的方式去上傳,是以後端在處理 multipart/mixed 的内容時,必須從 Stream 流中讀取。

二、HttpServletRequest 處理 multipart/mixed 請求

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            Part signPart = request.getPart(Constants.SIGN_KEY);
            Part appidPart = request.getPart(Constants.APPID_KEY);
            Part noncestrPart = request.getPart(Constants.NONCESTR_KEY);
            Map<String, String[]> paramMap = new HashMap<>(8);
            paramMap.put(signPart.getName(), new String[]{stream2Str(signPart.getInputStream())});
            paramMap.put(appidPart.getName(), new String[]{stream2Str(appidPart.getInputStream())});
            paramMap.put(noncestrPart.getName(), new String[]{stream2Str(noncestrPart.getInputStream())});
            // 其他處理
      }
           
private String stream2Str(InputStream inputStream) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
           

三、SpringMVC 處理 multipart/mixed 請求

SpringMVC 可以直接以 @RequestPart 注解接收 multipart/mixed 格式的請求參數。

@ResponseBody
    @RequestMapping(value = {"/token/user/uploadImage"}, method = {RequestMethod.POST, RequestMethod.GET})
    public AjaxList uploadImage(
             @RequestPart (required = false) String token,
             @RequestPart (required = false) String sign,
             @RequestPart (required = false) String appid,
             @RequestPart (required = false) String noncestr,
             @RequestPart MultipartFile file, HttpServletRequest request) {

             }