文件上传
新增一个前端上传入口
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传和下载</title>
</head>
<body>
<form action='http://localhost:8080/file/upload' method='post' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit'>上传</button>
</form>
</body>
</html>
上传代码如下
/**
* 文件上传
* @param file file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file){
// 获取上传文件时的名字
String filename = file.getOriginalFilename();
//获取文件后缀名
String suffixName = filename.substring(filename.lastIndexOf("."));
//文件保存路径
String path = "E:/test/";
//文件重命名 防止重复
filename = UUID.randomUUID()+filename;
//文件对象
File dest = new File(path,filename);
//判断路径是否存在 不存在则创建
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
System.out.println("文件上传名字"+filename);
System.out.println("后缀名"+suffixName);
System.out.println("文件对象"+dest);
//保存到服务器中
try {
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
下载代码
@RequestMapping("/download")
public void download(HttpServletResponse response){
// 文件地址,真实环境是存放在数据库中的
File file = new File("E:\\test\\哈哈哈.xlsx");
//创建文件输入流
try {
FileInputStream fls = new FileInputStream(file);
//设置文件下载响应头
response.setContentType("application/octet-stream");
//设置下载文件名 处理中文乱码
String fileName = URLEncoder.encode("哈哈哈.xlsx","UTF-8") ;
// 设置下载后的文件名以及header
response.addHeader("Content-disposition", "attachment;fileName=" + fileName);
//创建文件输出流
OutputStream outputStream = response.getOutputStream();
//设置每次读取字节
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fls.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
fls.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
下载不需要新增页面,浏览器直接输入地址,即可下载