利用SpringMVC上傳文件

m4ed 9年前發布 | 3K 次閱讀 Java SpringMVC

利用SpringMVC上傳文件,也可以一次上傳多個文件。

上傳多個文件的時候用MultipartFile[] file即可

頁面表單

<html>
    <head>
        <title>Upload a file please</title>
    </head>
    <body>
        <h1>Please upload a file</h1>
        <form method="post" action="/form" enctype="multipart/form-data">
            <input type="text" name="name"/>
            <input type="file" name="file"/>
            <input type="submit"/>
        </form>
    </body>
</html>

控制層JAVA代碼

@Controller
public class FileUploadController {

@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, 
    @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes();
        // store the bytes somewhere
       return "redirect:uploadSuccess";
   } else {
       return "redirect:uploadFailure";
   }
}

}</pre>

 本文由用戶 m4ed 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!