SpringMVC 的上传与下载
第一步:
pom.xml 里加入
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml/classmate -->
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.1.0</version>
</dependency>
第二步:
fileConfig 配置:
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
public class FileConfig {
@Bean
public CommonsMultipartResolver getMultipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("UTF-8");
//缓存最大值
commonsMultipartResolver.setMaxInMemorySize(10485760);
//上传文件的最大值
commonsMultipartResolver.setMaxUploadSize(40960);
return commonsMultipartResolver;
}
}
第三步:
controller层:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
public class FileController {
/**
* 文件上传
* @param uploadfile
* @param request
* @return
*/
@RequestMapping("springUpLoadTwo")
public Map<String,Object> upLoad(@RequestParam("file") MultipartFile uploadfile, HttpServletRequest request) throws FileNotFoundException {
Map<String,Object> result = new HashMap<>();
//获取文件大小
long size = uploadfile.getSize();
//获取文件类型
String contentType = uploadfile.getContentType();
System.out.println("文件类型="+contentType);
//获取文件名
String fileName = uploadfile.getOriginalFilename();
//获取文件后缀
String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
System.out.println("文件名= "+fileName);
//文件存放路径
String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/uploadfile"; //项目/target中
//String filePath = "F:\\fileTest"; //此处是绝对路径
System.out.println("存放地址= "+filePath);
//判断路径是否存在
File file = new File(filePath);
if(!file.exists()){
//不存在则创建一个
file.mkdir();
}
//将文件写入目标 (存放地址,文件名称+后缀)
file = new File(filePath, UUID.randomUUID()+fileSuffix);
try {
//上传到目标文件夹
uploadfile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
//返回给前端图片的名称 前端再点击存进数据库
result.put("fileName",file.getName());
return result;
}
//文件下载 (必须有文件名,否则报错)
@RequestMapping("/testDownload")
public ResponseEntity<byte[]> download() throws IOException {
//项目路径 (必须要加上文件名,否则报错)
String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/uploadfile/69a01884-d800-4e26-a63d-bc3b0d45533e.txt"; //项目/target中
File file = new File(filePath);
//创建文件 本地路径
//File file = new File("F:\\fileTest\\69a01884-d800-4e26-a63d-bc3b0d45533e.txt");
byte[] body = null;
//创建输入流(从硬盘读取数据)
InputStream is = new FileInputStream(file);
//创建字节数组并指定长度
body = new byte[is.available()];
//将数据从输入流导到输出流
is.read(body);
//创建请求头并设置指定值
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
//设置HTTP响应状态。
HttpStatus statusCode = HttpStatus.OK;
//创建响应实体对象
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
//下载方法二:
// 获取文件输入流
FileInputStream fileInputStream = new FileInputStream(new File("E:/", "file-name.txt"));
//文件下载
response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode("file-name.txt","UTF-8"));
//获取响应输出流
ServletOutputStream outputStream = response.getOutputStream();
//文件拷贝
IOUtils.copy(fileInputStream,outputStream);
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(outputStream);
}
//文件直接展示:
BufferedInputStream is = null;
OutputStream os = null;
try {
os = new BufferedOutputStream(response.getOutputStream());
is = new BufferedInputStream(stream);
FileCopyUtils.copy(is, os);
} catch (Exception e) {
logger.error("Stream Error,", e);
}
第四步:
写前端html
<form action="springUpLoadTwo" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
<a href="testDownload" id="xiazai">下载</a>
完工
PS:项目路径在target中