SpringMVC05_文件上传和下载

SpringMVC05_文件上传和下载


单文件上传
  • 添加两个文件上传需要的依赖:
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.5</version>
</dependency>
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.4</version>
</dependency>
  • upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/file/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="img"/>
        <input type="submit" value="上传"/>
    </form>
    <img src="${path}">
</body>
</html>
  • FileHandler
package com.blu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileHandler {

    @PostMapping("/upload")
    public String upload(MultipartFile img, HttpServletRequest request) {
        if (img.getSize() > 0) {
            String path = request.getServletContext().getRealPath("file");
            System.out.println(path);
            String name = img.getOriginalFilename();
            File file = new File(path, name);
            try {
                //把文件img的内容转给file
                img.transferTo(file);
                request.setAttribute("path","/file/"+name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload";
    }
}
  • 配置文件中添加文件上传组件:
<!-- 配置文件上传组件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
  • 运行测试(访问http://localhost:8080/upload.jsp打开文件上传页面,选择一个jpg文件上传)

  • 控制台打印:

C:\apache-tomcat-9.0.31-windows-x64\apache-tomcat-9.0.31\webapps\ROOT\file

在该路径下出现了自己上传的图片,但页面无法正常显示:
在这里插入图片描述
解决办法:在web.xml中添加对.jpg静态资源文件的忽略处理即可

<servlet-mapping>
	<servlet-name>default</servlet-name>
	<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
  • 修改后重新运行,上传后的图片可正常显示:
    在这里插入图片描述

多文件上传
  • 添加以下两个依赖以支持JSTL语句:
<dependency>
	<groupId>jstl</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
  • 多文件上传页面uploads.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/file/uploads" method="post" enctype="multipart/form-data">
        file1:<input type="file" name="imgs"/><br/>
        file2:<input type="file" name="imgs"/><br/>
        file3:<input type="file" name="imgs"><br/>
        <input type="submit" value="上传"/>
    </form>
    <c:forEach items="${files}" var="file">
        <img src="${file}" width="300px">
    </c:forEach>
</body>
</html>
  • Handler
@PostMapping("/uploads")
public String uploads(MultipartFile[] imgs, HttpServletRequest request){
	List<String> files = new ArrayList<>();
	for (MultipartFile img:imgs){
		if (img.getSize() > 0) {
			String path = request.getServletContext().getRealPath("file");
			System.out.println(path);
			String name = img.getOriginalFilename();
			File file = new File(path, name);
			try {
				img.transferTo(file);
				files.add("/file/"+name);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	request.setAttribute("files",files);
	return "uploads";
}
  • 测试(访问http://localhost:8080/uploads.jsp,上传三张图片)在这里插入图片描述
  • 页面显示:
    在这里插入图片描述
  • C:\apache-tomcat-9.0.31-windows-x64\apache-tomcat-9.0.31\webapps\ROOT\file 目录:
    在这里插入图片描述

文件下载
  • 首先上传三张.jpg格式的图片:
    在这里插入图片描述
  • download.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
	<head>
    	<title>Title</title>
	</head>
	<body>
    	<a href="/file/download/1">1.jpg</a><br>
    	<a href="/file/download/2">2.jpg</a><br>
    	<a href="/file/download/3">3.jpg</a>
	</body>
</html>
  • Handler
@GetMapping("/download/{name}")
public void download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response){
	if (name != null){
		name += ".jpg";
		String path = request.getServletContext().getRealPath("file");
		File file = new File(path,name);
		OutputStream outputStream = null;
		if (file.exists()){
			response.setContentType("application/forc-download");
			response.setHeader("Content-Disposition","attachment;filename="+name);
			try {
				outputStream = response.getOutputStream();
				outputStream.write(FileUtils.readFileToByteArray(file));
				outputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (outputStream != null){
					try {
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章