控制器代码:
package com.wisely.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/file/")
public class FileController {
@RequestMapping("upload")
@ResponseBody
public String upload(@RequestParam MultipartFile file) {
System.out.println("file.name = "+file.getOriginalFilename());
//获取文件名
String fileName = file.getOriginalFilename();
//获取后缀名
//String suffixName = fileName.substring(fileName.lastIndexOf("."));
//文件保存路径
String filePath = "G:/upload/";
//文件名处理
fileName = filePath + UUID.randomUUID().toString().replace("-", "") + fileName;
//创建文件对象
File dest = new File(fileName);
//如果文件夹不存在则创建
if(!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "上传失败";
}
@RequestMapping("download")
public void download(HttpServletResponse response) throws IOException {
File file = new File("G:\\upload\\test.txt");
FileInputStream fis = new FileInputStream(file);
//下载文件而不是打开
response.setContentType("application/force-download");
//设置下载文件名
response.addHeader("Content-disposition", "attachment;fileName=test.txt");
OutputStream os = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1) {
os.write(buf,0,len);
}
fis.close();
}
}
前端代码:
<!--文件上传 -->
<div>
<form action="/file/upload" enctype="multipart/form-data" method="post">
文件:<input type="file" name="file"><br>
<button type="submit">上传</button>
</form>
</div>
<hr>
<!--文件下载 -->
<div>
<a href="/file/download">下载</a>
</div>