版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29451823/article/details/82782284
- 上传下载文件
package com.imooc.web.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.imooc.dto.FileInfo;
/**
*
* @author cjj
* @date 2018年9月20日
* @email [email protected]
*/
@RestController
public class FileController {
private String path = "H:\\spring security学习视频\\源码\\project\\p1o6vt\\imooc-security-demo\\src\\main\\java\\com\\imooc\\web\\controller";
/**
* 上传文件
* @param file
* @return
* @throws Exception
*/
@PostMapping("/file")
public FileInfo upload(MultipartFile file) throws Exception {
System.out.println(file.getName());//获取表单中文件组件的名字
System.out.println(file.getOriginalFilename());//获取上传文件的名字
System.out.println(file.getSize());//文件的上传大小
//根据路径+时间戳+文件后缀名来创建文件
File localFile = new File(path, new Date().getTime() + ".txt");
//如果是传入服务器 file.getInputStream();用输入输出流来读取
//储存为本地文件
file.transferTo(localFile);
return new FileInfo(localFile.getAbsolutePath());
}
/**
* 下载文件
* @param id
* @param request
* @param response
* @throws IOException
* @throws FileNotFoundException
*/
//@GetMapping("/{id}")
public void downLoad(@PathVariable String id,HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException, IOException {
//JDK 1.7后 可以在try中自动关闭流文件
//inputStream 输入 读,OutputStream输出,写
try(InputStream inputStream = new FileInputStream(new File(path, id + ".txt"));
OutputStream outputStream = response.getOutputStream();) {
//设置响应类型
response.setContentType("application/x-download");
//Content-disposition是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 Internet Explorer 接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。
response.addHeader("Content-Disposition", "attachment;filename=text.txt");
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
}
}