一、文件上传(方式一)
前端表单要求:为了能上传文件,必须将表单的 method 设置为 POST,并将 enctype 设置为multipart/form-data
。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据。
Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类: CommonsMultipartResolver。因此 SpringMVC 的文件上传还需要依赖 Apache Commons FileUpload的组件。
1、springmvc-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.lxc.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--ID必须为multipartResolver,否则就400问题-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="1048576"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
这个bena的id必须为:multipartResolver ,非常之重要,我的老师就在这栽过坑!!!
2、前端的表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit">
</form>
</body>
</html>
3、导入上传文件的 jar 包 commons-fileupload
Maven 会自动帮我们导入它的依赖包 commons-io
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
我们会使用它的实现类 CommonsMultipartFile , 常用方法如下:
方法 | 说明 |
---|---|
String getOriginalFilename() | 获取上传文件的原名 |
InputStream 、getInputStream() | 获取文件流 |
void transferTo(File dest) | 将上传文件保存到一个目录文件中 |
4、Controller 类的编写
注:必须加上 @RequestParam , 否则也会报错!作用是用来实现封装!
package com.lxc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@Controller
public class FileUploadController {
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传文件名称
String filename = file.getOriginalFilename();
if ("".equals(filename)) {
return "redirect:/index.jsp";
}
System.out.println("文件上传名称" + filename);
//上传保存路径
String path = request.getServletContext().getRealPath("/upload");
File realpath = new File(path);
if (!realpath.exists()) {
realpath.mkdirs();
}
System.out.println("上传文件保存地址" + realpath);
InputStream inputStream = file.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File(realpath, filename));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return "redirect:/index.jsp";
}
}
二、文件上传(方式二)
方式二是采用 file.Transto 来上传,我们只需要改动 Controller 类即可
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
三、文件下载
文件下载步骤:
- 设置 response 响应头
- 读取文件 – InputStream
- 写出文件 – OutputStream
- 执行操作
- 关闭流 (先开后关)
1、Controller 类的编写
//文件下载
@RequestMapping(value = "/download")
public String downLoad(HttpServletResponse response) throws IOException {
//图片的路径
String path = "C:\\Users\\lenovo\\Desktop\\";
// 图片的名字
String filename = "picture.jpg";
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");//二进制流传输数据
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
File file = new File(path, filename);
FileInputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return null;
}
2、前端代码
前端代码就是一个简单的链接
<a href="/download">点击下载</a>
进行测试,图片可以正常下载。