SpringMVC文件的上傳與下載實現

單文件上傳

首先創建項目,開發工具是IDEA,選擇Spring項目,勾選上Spring和SpringMVC。
然後命名,最後完成。

默認生成配置文件在web/WEB-INF下。

首先導入需要的jar包。
在這裏插入圖片描述
如果是創建的maven工程,導入以下依賴

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
然後添加都本項目的依賴中。
在這裏插入圖片描述
開始修改配置。
Web.xml文件,配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <!--上傳文件大小限制-->
        <property name="maxInMemorySize" value="1048576"></property>
        <!--字符編碼-->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    <bean id="nameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="50"></property>
    </bean>

    <mvc:view-controller path="success" view-name="success"></mvc:view-controller>
    <mvc:view-controller path="index" view-name="index"></mvc:view-controller>
    <!--視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="resolver">
        <property name="prefix" value="/ch10/"></property>
        <property name="suffix" value=".jsp"></property>
        <property name="order" value="0"></property>
    </bean>
    <!--開啓包掃描-->
    <context:component-scan base-package="com.springmvc" annotation-config="true"/>
    <!--解析註解-->
    <mvc:annotation-driven/>
    
</beans>


因爲在dispatcher-servlet.xml中視圖解析器解析的是ch10開頭的文件,並且後綴名是.jsp結尾。因此需要在web文件夾下創建ch10文件夾,之後的index.jsp和success.jsp都放在這裏。

index.jsp

<html>
<head>
    <title>文件上傳</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/fileUpload">
    選擇文件: <input type="file" name="file"><br/>
    <br/>
    <input type="submit" value="提交">
</form>
</body>
</html>

裏面沒什麼內容簡單的一個表單,需要注意的是文件上傳的請求方式必須是以POST提交表單。請求的路徑是/fileUpload。
success.jsp

<html>
<head>
    <title>文件上傳成功</title>
</head>
<body>
<h1>文件上傳成功!</h1>
    ${fileUrl}
</body>
</html>

如果文件上傳成功就跳轉到success.jsp這個頁面,顯示文件上傳成功,並顯示文件的路徑。

最後在src文件夾下創建controller包,並創建FileUploadController.java

@Controller
public class FileUploadController {

    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
        //服務端文件夾物理路徑
        String realPath = request.getSession().getServletContext().getRealPath("upload");
        //獲取文件名
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        //創建一個File對象表示目標文件
        File file1 = new File(realPath,filename);

        //如果目標路徑不存在就創建
        if (!file1.exists()){
            file1.mkdirs();
        }

        //上傳文件到指定目錄
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.put("fileUrl",request.getContextPath()+"/upload/"+filename);
        return "success";
    }

}

最後的項目結構是這樣的。
在這裏插入圖片描述
然後配置Tomcat,啓動。
在這裏插入圖片描述
點左上角的 + 號。
選擇tomcat在local下創建。之後配置啓動時的瀏覽器
在這裏插入圖片描述
在這裏插入圖片描述
最後啓動Tomcat。在瀏覽器中訪問 localhost:8080/ch10
在這裏插入圖片描述
然後選擇圖片,圖片最大爲1M,最後點擊提交。
在這裏插入圖片描述
同時控制檯輸出fileName
在這裏插入圖片描述
圖片在以下目錄下查看。
在這裏插入圖片描述

多文件上傳

首先創建一個uploadFiles.jsp

<html>
<head>
    <title>多文件上傳</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">

    文件描述:<input type="text" name="description"><br><br>
    選擇文件: <input type="file" name="files" multiple="multiple"><br/><br>
    <br/>
    <input type="submit" value="提交">
</form>
</body>
</html>

然後在FileUploadController中寫一個upload方法,用來處理多文件上傳請求。

@RequestMapping("/upload")
    public String uploadFiles(@RequestParam String description, @RequestParam(value = "files", required = false) List<MultipartFile> files, HttpServletRequest request) {
        //判斷文件是否存在
        if (!files.isEmpty() && files.size() > 0) {
            //遍歷上傳的多個文件
            for (MultipartFile file : files) {
                //獲取上傳的文件名
                String filename = file.getOriginalFilename();

                //獲取上傳的文件地址
                String dirPath = request.getServletContext().getRealPath("/upload/");
                File filePath = new File(dirPath);
                //如果保存的文件地址不存在就創建
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                //使用UUID重命名新文件
                String newFilename = description + UUID.randomUUID() + "_" + filename;
                try {
                    file.transferTo(new File(dirPath + newFilename));
                } catch (IOException e) {
                    e.printStackTrace();
                    //如果拋出異常就返回錯誤頁面
                    return "error";
                }
            }
            //以上執行過程都沒有問題就返回成功頁面
            return "success";
        }


        return "error";
    }

啓動tomcat服務器,輸入localhost:8080/ch10/uploadFiles.jsp
選中多個文件,然後提交

這裏選中多個文件是ctrl+鼠標左鍵,可以選中多個文件
在這裏插入圖片描述
在這裏插入圖片描述

既然上傳成功了那就到項目中去看看傳到哪個文件夾下了
在這裏插入圖片描述

文件的下載

文件下載就是將服務器的文件下載到本地。服務端會在頁面上面給出超鏈接,就可以實現文件下載了。但是如果超鏈接中包含中文有可能下載失敗(這個Goole和Firefox就沒事,不過IE和360就不知道了)。
在上傳成功的jsp中添加一個超鏈接。

<a href="/fileDownload?fileName=${fileName}">${fileName}下載</a>

然後編寫文件上傳代碼。

@RequestMapping("/fileDownload")
  public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam String fileName, Model model) throws Exception {

        //下載文件路徑
        String realPath = request.getServletContext().getRealPath("/upload/");
        //創建文件對象
        File file = new File(realPath+File.separator+fileName);

        //設置響應頭
        HttpHeaders headers = new HttpHeaders();
        //解決中文亂碼問題
        String downloadFileName = new String(fileName.getBytes(),"ISO-8859-1");
        //通知瀏覽器下載文件
        headers.setContentDispositionFormData("attachment",downloadFileName);
        //以二進制文件流的形式下載文件數據
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //返回封裝後的下載數據
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}

最後開啓服務器,測試一下
訪問localhost:8080/ch10/
然後選擇單個文件上傳,上傳成功後會顯示如下界面。

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
至此文件下載完成。

以上有不對的地方歡迎指出,分享想法,一起nb!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章