/**
* 文件上传
*
* @param file 上传的文件
* @param path 文件名称
* @throws IOException
*/
@RequestMapping(value = "/FileUpload")
public void fileUpload(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(value = "name", required = false) String path) throws IOException {
/* 创建文件:存储上传的文件 */
File lf = new File("D:/传输测试文档.txt");
/* 将上传的文件内容转换到本地文件 */
file.transferTo(lf);
}
/**
* 文件下载
*
* @param response 响应体
* @throws Exception
*/
@RequestMapping(value = "/FileDownload")
public void downloadLocal(HttpServletResponse response) throws Exception {
/* 对文件名进行转码处理,否则下载的文件没有名称 */
String fileName = URLEncoder.encode("账号密码.txt", "UTF-8");
/* 文件存储路径 */
String filePath = "D:/账号密码.txt";
/* 创建输入流 */
InputStream inputStream = new FileInputStream(filePath);
/* 让浏览器接收到这份资源的时候,以下载的方式处理,而不是直接展示 */
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
/* 单次读取大小 */
byte[] content = new byte[1024];
int len;
/* 读取文件内容 */
while ((len = inputStream.read(content)) > 0) {
/* 写入输出流 */
response.getOutputStream().write(content, 0, len);
}
/* 关闭输入流 */
inputStream.close();
}
spring boot实现文档上传下载(笔记)
最新推荐文章于 2022-08-04 10:00:29 发布