工程代码
package zhw.example.zhw.fileModule.fileController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
@Controller
@RequestMapping(value = "file")
public class fileController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@ResponseBody
@RequestMapping(value = "upload")
public void upload(@RequestParam("file")MultipartFile file){
String fileName = file.getOriginalFilename();
String filePath = "D:/upload/";
fileName = filePath + UUID.randomUUID() + "_" + fileName;
log.info("fileName:"+fileName);
File dest = new File(fileName);
if(!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
log.info("file save succ");
} catch (Exception e) {
e.printStackTrace();
log.info("fileName save fail");
}
}
@GetMapping(value = "download")
public void download(@RequestParam("filename") String fileName, HttpServletResponse response) throws IOException {
String filename = "D:\\upload\\" + fileName;
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
response.setContentType("application/force-download");
response.addHeader("Content-disposition", "attachment;fileName=" + filename);
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();
}
}
测试
上传测试
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/38e01e7eb4a8241065270ea563596b81.png)
下载测试
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1f8155bae1d4a6baa79baa12b9205ded.png)