实现文件的上传和下载
package com.atguigu.mvc.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
//实现文件的上传和下载
@Controller
public class FileUpAndDownController {//target目录是部署到服务器的内容
@RequestMapping("/testDown")
public ResponseEntity testResponseEntity(HttpSession session) throws IOException {//获取Session会话对象
//ResponseEntity 作为控制器方法的返回值类型响应到浏览器的响应报文 自定义类型响应报文
//获取 ServletContext 工程对象
ServletContext servletContext = session.getServletContext();//ServletContext代表当前整个工程
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/wallhaven-x8k5wz.png");
System.out.println(realPath);
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];//available() 输入流文件的有字节数
//bytes 响应体 传输的数据
//将流读到字节数组中
is.read(bytes);
//响应头
//创建HttpHeaders对象设置响应头信息
MultiValueMap headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=wallhaven-x8k5wz.pg");//内容配置 附件文件名称 以附件的方式下载
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
@RequestMapping("/testUp")
public String testUp(MultipartFile photo ,HttpSession httpSession) throws IOException {//获取 Session对象 ——> 创建ServletContext应用对象 ——> 获取RealPath
//文件名称
String originalFilename = photo.getOriginalFilename();//获取待上传的文件名称
//将文件名设置为 UUID+后缀防止文件重名
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//后缀
String uuid = UUID.randomUUID().toString();//随机
originalFilename = uuid + suffix;
ServletContext httpSessionServletContext = httpSession.getServletContext();
//路径
String photoPath = httpSessionServletContext.getRealPath("photo");//上传至服务器photo路径下
File file = new File(photoPath);//file文件代表photoPath目录 --> 判断目录是否存在
if (!file.exists()) file.mkdir();//判断photoReal文件路径是否存在,若不存在则创建目录
//目录已创建成功
//设置最终上传路径
String finalPath = photoPath + File.separator + originalFilename;//分隔符 File.separator
//上传
photo.transferTo(new File(finalPath));//transferTo 先读再写
return "success";
}
}
测试文件的上传和下载
下载 wallhaven-x8k5wz.png