Java 處理 multipart/mixed 請求

1、multipart/mixed 請求

  multipart/mixed 和 multipart/form-date 都是多文件上傳的格式。區別在於,multipart/form-data 是一種特殊的表單上傳,其中普通字段的內容仍是按照通常的請求體構建,文件字段的內容按照 multipart 請求體構建,後端在處理 multipart/form-data 請求的時候,會在服務器上創建臨時的文件夾存放文件內容,可參看這篇文章。而 multipart/mixed 請求會將每一個字段的內容,無論是普通字段仍是文件字段,都變成 Stream 流的方式去上傳,所以後端在處理 multipart/mixed 的內容時,必須從 Stream流中處理。html

2、Servlet 處理 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) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

3、SpringMVC 處理 multipart/mixed 請求

@ResponseBody
    @RequestMapping(value = {"/token/user/uploadImage.yueyue", "/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 avatar, HttpServletRequest request) {

             }
相關文章
相關標籤/搜索