SpringMVC文件上傳

SpringMVC爲文件上傳提供了直接的支持,這種支持是用即插即用的 MultipartResolver實現的。SpringMVC使用Apache Commons FileUpload技術實現了一個 MultipartResolver實現類: CommonsMultipartResolver。所以,SpringMVC的文件上傳還須要依賴Apache Commons FileUpload的組件。

1. 添加pom依賴

<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.3</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>

2. 配置文件上傳bean

在spring mvc配置文件中增長一個文件上傳bean。html

<!-- SpringMVC上傳文件時,須要配置MultipartResolver處理器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

3.文件上傳

文件上傳是項目開發中最多見的功能。爲了能上傳文件,必須將表單的method設置爲 POST,並將 enctype設置爲 multipart/form-data。只有在這樣的狀況下,瀏覽器纔會把用戶選擇的文件以二進制數據發送給服務器。

上傳文件界面:upload_form.jspjava

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上傳</title>
</head>
<body>

<!-- 上傳單個對象 注意表單的method屬性設爲post,enctype屬性設爲multipart/form-data -->
<form method="POST" action="/SpringMVCDemo1/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="上傳" />
</form>

<!-- 上傳多個對象 注意表單的method屬性設爲post,enctype屬性設爲multipart/form-data -->
<form method="POST" action="/SpringMVCDemo1/uploadMultiFiles" enctype="multipart/form-data">
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p>文件3:<input type="file" name="file" /></p>
    <!-- 同時傳遞其餘業務字段 -->
    <p>用戶名:<input type="text" name="userName" /></p>
    <p>密碼:<input type="password" name="password" /></p>
    <p><input type="submit" value="上傳" /></p>
</form>
</body>
</html>

上傳結果返回界面:upload_result.jspweb

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>上傳結果爲:${message}</h2>
</body>
</html>

注意:要提早建立好存儲文件的文件夾,好比個人路徑爲:"D:staticResourcesTestimgupload"。spring

FileController.java瀏覽器

@Controller
@RequestMapping("/SpringMVCDemo1")
public class FileController {
    /**
     * 跳轉到上傳頁面
     * @GetMapping 是一個組合註解,是@RequestMapping(method = RequestMethod.GET)的縮寫。
     */
    @GetMapping("/gotoUploadForm")
    public String index() {
        return "/upload_form.jsp";
    }

    /**
     * 上傳單個文件
     * 經過MultipartFile讀取文件信息,若是文件爲空跳轉到結果頁並給出提示;
     * 若是不爲空讀取文件流並寫入到指定目錄,最後將結果展現到頁面
     * @param multipartFile
     * @PostMapping 是一個組合註解,是@RequestMapping(method = RequestMethod.POST)的縮寫。
     */
    @PostMapping("/upload")
    public String uploadSingleFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        if (multipartFile.isEmpty()){
            request.setAttribute("message",  "Please select a file to upload '");
            return "/upload_result.jsp";
        }

        try {
            String contentType = multipartFile.getContentType();
            String originalFilename = multipartFile.getOriginalFilename();
            byte[] bytes = multipartFile.getBytes();
            System.out.println("上傳文件名爲-->" + originalFilename);
            System.out.println("上傳文件類型爲-->" + contentType);
            System.out.println("上傳文件大小爲-->"+bytes.length);

            //filePath爲存儲路徑
            String filePath = "d:/staticResourcesTest";
            System.out.println("filePath-->" + filePath);
            //存儲在staticResourcesTest下的imgupload文件夾下
            File parentPath = new File(filePath, "imgupload");
            System.out.println("上傳目的地爲-->"+parentPath.getAbsolutePath());
            try {
                File destFile = new File(parentPath,originalFilename);//上傳目的地
                FileUtils.writeByteArrayToFile(destFile,multipartFile.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.setAttribute("message",  "You successfully uploaded '" + multipartFile.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/upload_result.jsp";
    }

    /**
     * 上傳多個文件,同時接受業務數據
     * @param origFiles
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/uploadMultiFiles")
    public String uploadMultiFiles(@RequestParam("file") List<MultipartFile> origFiles, HttpServletRequest request, User user) {
        //User爲實體類
        System.out.println("User=="+user);
        if (origFiles.isEmpty()) {
            request.setAttribute("message",  "Please select a file to upload '");
            return "/upload_result.jsp";
        }

        try {
            for (MultipartFile origFile : origFiles) {
                String contentType = origFile.getContentType();
                String fileName = origFile.getOriginalFilename();
                byte[] bytes = origFile.getBytes();
                System.out.println("上傳文件名爲-->" + fileName);
                System.out.println("上傳文件類型爲-->" + contentType);
                System.out.println("上傳文件大小爲-->"+bytes.length);

                String filePath = "d:/staticResourcesTest";
                System.out.println("上傳目的地爲-->"+filePath);
                try {
                    //上傳目的地(staticResourcesTest文件夾下)
                    File destFile = new File(filePath,fileName);
                    FileUtils.writeByteArrayToFile(destFile,origFile.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            request.setAttribute("message",  "You successfully uploaded '");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "/upload_result.jsp";
    }
}
相關文章
相關標籤/搜索