1、下载
package com.resoft.ssm.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 javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
@Controller
public class FileController {
@RequestMapping("/test/down")
public ResponseEntity<byte[]> testResponseEntity(HttpSession httpsession) throws IOException {
//获取servletcontext对象
ServletContext servletContext = httpsession.getServletContext();
//获取服务器中文件的真实路径:
//getRealPath():方法本身用来获取系统的绝对路径
//getRealPath(""):方法中写文件的路径:相对路径
//getRealPath():本质上是字符串的拼接
String realPath = servletContext.getRealPath("img");
//File.separator : 系统目录中的间隔符
realPath = realPath + File.separator + "a.png";
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组:is.available():获取输入流所对应文件的字节数
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象,设置响应头的信息
MultiValueMap<String ,String > headers = new HttpHeaders();
//设置下载方式,以及下载的文件的名字
//attachent:以附件形式下载
//filename=1.jpg: 设置下载的名字
headers.add("Content-Disposition","attachent;filename=1.jpg");
//设置相应状态码
HttpStatus httpStatus = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,headers,httpStatus);
//关闭输入流
is.close();
return responseEntity;
}
}
2 上传文件
(1)方法:
@RequestMapping("/test/up")
public String fileUp(MultipartFile photo,HttpSession httpSession) throws IOException {
//获取上传的文件的文件名称
String fileName = photo.getOriginalFilename();
//获取文件后缀
String hzName = fileName.substring(fileName.lastIndexOf("."));
//获取uuid
String uuid = UUID.randomUUID().toString();
//拼接一个新的文件名称:uuid + 后缀
fileName = uuid + hzName;
//获取系统目录的真实路径
ServletContext servletContext = httpSession.getServletContext();
//获取需要上传到的文件夹的位置
String realPath = servletContext.getRealPath("photo");
//判断该文件夹是否存在
//将该文件路径指定为file,如果不存在,就创建该文件夹
File file = new File(realPath);
if (!file.exists()){
//如果不存在,就创建
file.mkdir();
}
//指定上传文件的路径
String finalPath = realPath + File.separator + fileName;
//上传文件:将文件上传到指定的路径处
photo.transferTo(new File(finalPath));
return "success";
}
(2)配置文件:
<!--配置文件上传解析器-->
<!--springmvc通过 id 来获取到文件解析器,且 id 固定-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>