使用RequestParam或HttpServletRequest獲取上傳的檔案

花繁柳密處發表於2021-01-03

前端(注意formmethodenctype):

<form action="/upload" id="form" method="post" enctype="multipart/form-data">
    姓名:<input type="text" id="name" name="name"><br>
    檔案:<input type="file" name="myFile"><br>
    <button type="submit">提交</button>
</form>

後臺:

@RequestMapping("/upload")
@ResponseBody
public JsonModel upload(String name, @RequestParam("myFile")MultipartFile file1, HttpServletRequest request){
    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
    MultipartFile file2 = mRequest.getFile("myFile");

    System.out.println(name);
    System.out.println(file1.getOriginalFilename());
    System.out.println(file2.getOriginalFilename());
    return new JsonModel(true, "提交成功");
}

相關文章