Java handles multipart / mixed requests

1、 Multipart / mixed request

  multipart / mixed and multipart / form date are formats for uploading multiple files. The difference is that multipart / form data is a special form upload, in which the contents of ordinary fields are still constructed according to the general request body, and the contents of file fields are constructed according to the multipart request body. When processing multipart / form data requests, the back end will establish a temporary folder on the server to store file contents. See this article; Multipart / mixed requests will upload the contents of each field, whether ordinary fields or file fields, into a stream stream. Therefore, when processing the contents of multipart / mixed, the backend must read from the stream stream stream.

2、 HttpServletRequest handles multipart / mixed requests

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

3、 Spring MVC handles multipart / mixed requests

Spring MVC can directly receive request parameters in multipart / mixed format with @ requestpart annotation.

    @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) {

             }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>