上传文件

单文件和多文件上传
单文件上传(只能上传单个文件)

MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
Set> set = mulRequest.getFileMap().entrySet();

多文件上传(可以上传单个,多个使用数组方式)

①
MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
List files = mulRequest.getFiles("filePath");
②
MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
Set>> set = multipartRequest.getMultiFileMap().entrySet();

提交文本信息和文件时
①可以使用Map接收文本,HttpServletRequest接收文件。formData接收下图中圈出来的两部分东西。其实第二圈起来的text部分内容也可以从HttpServletRequest中拿到,取到的是一个json字符串,再转成对象。

json字符串转对象
InvestDetailCash investDetailCash = new InvestDetailCash();

        try {
            String json = request.getParameter("content");
            if (!StringUtils.isEmpty(json)) {
                ObjectMapper oMapper = new ObjectMapper();
                oMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                investDetailCash = oMapper.readValue(json, InvestDetailCash.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
/**
     * 导入
     */
    @RequestMapping(value = "/leadingIn", method = RequestMethod.POST)
    public ResponseObj leadingIn(@RequestParam Map formData,
                                          HttpServletRequest request,
                                          Map files) {
}

完整方法

    /**
     * 导入
     */
    @RequestMapping(value = "/leadingIn", method = RequestMethod.POST)
    public ResponseObj leadingIn(@RequestParam Map formData,
                                          HttpServletRequest request,
                                          Map files) {
        //测试
        try {
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            Set> set = mulRequest.getFileMap().entrySet();
            Map listFile = new LinkedHashMap<>();
            System.out.println("个数" + set.size());
            for (Map.Entry each : set) {
                String fileName = each.getKey();
                MultipartFile file = each.getValue();
                //这里需要上传FTP
                try {
                    listFile.put(fileName, file.getInputStream());
                } catch (Exception ex) {
                    return new ResponseObj<>(false, null);
                }
            }

            String formjson = mulRequest.getParameter("content");
            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

//            boolean result = iInstallWorkOrder.upLoadFile(listFile);
            boolean result = true;

            return new ResponseObj<>(result, null);
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return new ResponseObj<>(false, null);
        }

    }
图二.png

你可能感兴趣的:(上传文件)