上传类:【配置文件参照博客中的Ajax与Json】
@Controller
public class EmployeeHandler {
@RequestMapping()
public String up(String desc, MultipartFile uploadFile, HttpSession session) throws Exception{
//获取上传文件的名称
String fileName = uploadFile.getOriginalFilename();
//防止重名,如果重名name随机起名
String finalFileName=UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
//获取上传的时存储的位置
/**
* getRealPath("photo"),路径为空字符串是到工程下,字符串是什么,就是工程下的什么具体路径
* File.separator表示斜杠
* finalFileName表示上传文件名
*/
String path=session.getServletContext().getRealPath("photo")+ File.separator+finalFileName;
//创建一个此目录下的一个空文件
File file = new File(path);
//MVC独特:将上传的文件转为上边的空文件的位置
uploadFile.transferTo(file);
//返回视图
return "success";
}
文件下载【返回响应实体】
@Controller
public class EmployeeHandler {
/**
* 文件下载【返回的是响应实体】
* @param session
* @return
* @throws Exception
*/
@RequestMapping("/down")
public ResponseEntity<byte[]> down(HttpSession session) throws Exception{
//下载的文件路径
String realPath=session.getServletContext().getRealPath("photo");
String finalPath=realPath+File.separator+"1.jpg";
InputStream is=new FileInputStream(finalPath);
//available()获取输入流所读取的文件最大数
byte[] b=new byte[is.available()];
//读取数据,将文件数据读到数组中
is.read(b);
//设置请求头
HttpHeaders headers=new HttpHeaders();
//头文件属性+值,attachment是附件;filename是重命名
headers.add("Content-Disposition","attachment;filename=gaiming.jpg");
//设置响应状态
HttpStatus statusCode=HttpStatus.OK;
//设置最终
ResponseEntity<byte[]> entity = new ResponseEntity<>(b, headers, statusCode);
//关闭流
is.close();
return entity;
}
1224

被折叠的 条评论
为什么被折叠?



