导入pom文件
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
xml配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000000"></property>
<property name="maxUploadSizePerFile" value="1000000000"></property>
</bean>
前端页面
<b>文件上传</b>
<form method="post" action="/file/upload" enctype="multipart/form-data">
<input type="file" name="file" placeholder="选择文件">
<input type="submit" value="上传">
</form>
控制层部分
package com.zmc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class FileController {
/**
*1.在项目内部或资管理器中创建文件上传的文件夹
* 2.判断目录是否存在,不存在则创建
* 3.获取文件原始名
* 4.获取文件后缀名
* 5.构建文件上传具体路径
*6.最后一步,上传
*/
@RequestMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request, Model m) throws IOException {
// (创建)设置文件上传目录 (项目内部)
String uploadPath=request.getServletContext().getRealPath("uploadPath");
// 上传自定义电脑资源管理器
// String uploadPath="D:/aaa";
// 判断目录是否存在,不存在就创建
File file1=new File(uploadPath);
if (!file1.exists()) {
file1.mkdirs();
}
// 获取文件原始名
String originalName=file.getOriginalFilename();
// 获取文件后缀名
String suffix=originalName.substring(originalName.lastIndexOf("."));
// 构建文件上传具体路径
String detailPath=uploadPath.concat(File.separator).concat(UUID.randomUUID().toString()).concat(suffix);
file.transferTo(new File(detailPath));
m.addAttribute("detailPath",detailPath);
return "success";
}
}
文件下载
@RequestMapping("/downLoad")
public ResponseEntity<byte[]> downLoad(HttpServletRequest request, String fileName) throws IOException {
// 获取文件文件地址信息(在项目内部)
String upload = request.getServletContext().getRealPath("upload");
// 拼接出具体路径,判断文件是否存在
File file1 = new File(upload.concat(File.separator).concat(fileName));
if (!file1.exists()) {
return null;
}
// 创建标头文件对象
HttpHeaders headers = new HttpHeaders();
// 解决乱码问题
String s = new String(fileName.getBytes(StandardCharsets.UTF_8), "iso-8859-1");
// 以下载方式打开文件
headers.setContentDispositionFormData(s, fileName);
// 二进制流
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file1),headers, HttpStatus.CREATED);
}