Tag Archives: Upload file

JAVA: How to Use Multipartfile to upload Files

@PostMapping("upload")
public ResponseVo upload(@RequestParam("files[]") MultipartFile[] files) {
    Map<String, Object> resultMap = new HashMap<>();
    if (ArrayUtils.isEmpty(files)) {
        //resultMap.put("message", MessageUtil.getMessage("upload.error.no_files"));
        return new ResponseVo(ErrorCode.ACTION_ERROR).setMsg("没有上传文件");
    }
    MultipartFile multipartFile = files[0];
    File tmpFile = new File(System.currentTimeMillis() + "_" + multipartFile.getOriginalFilename());
    try (BufferedOutputStream outBuff = new BufferedOutputStream(new FileOutputStream(tmpFile)); BufferedInputStream inBuff = new BufferedInputStream(multipartFile.getInputStream())) {
        // Buffered arrays
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }
        // Flush the output stream of this buffer
        outBuff.flush();
        resultMap.put("message", MessageUtil.getMessage("upload.success"));
        resultMap.put("data", tmpFile);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseVo().setMsg("upload failed");
    } finally {
        FileUtils.deleteQuietly(tmpFile);
    }
    return new ResponseVo().setData(resultMap);
}

Result of postman call:

</ div>