配置ssm整合框架的环境 第三部分
文件上传
springMVC的文件上传仍然基于apache common-fileupload。
- 添加fileupload;io两个文件上传的jar包;
- 在springmvc.xml中配置文件上传解析对象。
<!--文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property><!--上传中文文件名-->
<property name="maxUploadSize" value="50000000"></property><!--上传文件最大大小-->
<property name="maxInMemorySize" value="10000000"></property><!--临时文件的存储域-->
<property name="uploadTempDir" value="/upload/tmp"></property><!--临时文件存储目录-->
</bean>
- 写文件上传处理器
package com.javasm.sys.handler;
import com.javasm.sys.entity.ResponseBean;
import com.javasm.sys.entity.StatusCode;
import com.javasm.sys.until.DateUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Controller
public class FileHandler {
@PostMapping("upload")
public ResponseEntity doupload(MultipartFile ifile, HttpServletRequest req){
String name = ifile.getName();//参数名
String fileName = ifile.getOriginalFilename();//文件名
String realPath = req.getServletContext().getRealPath("/");//得到根路径
String savePath ="upload"+fileName;//得到upload的路径
String saveFile = realPath+"/"+fileName;//拼接下载文件路径
try {
byte[] bytes = ifile.getBytes();//文件内容(直接放到数组里面了),适合小文件
// InputStream inputStream = ifile.getInputStream();//文件内容(还在流中,需要一点一点的读取),适合大文件
long size = ifile.getSize();//文件大小
FileUtils.writeByteArrayToFile(new File(saveFile),bytes);//写字节数组到一个文件内,内部创建流内部自动关
} catch (IOException e) {
e.printStackTrace();
}
//将上传的文件和具体的用户关联起来
Map<String,String> map = new HashMap<>();
map.put("SAVE_PATH",savePath);// /upload/aaaa.md
map.put("REAL_NAME",fileName);
map.put("UPLOAD_TIME",DateUtils.getCurrentTime()); //用工具类上传毫秒数给前端
return ResponseEntity.ok(new ResponseBean(StatusCode.OPS_SUC,map));
}
}
下载文件
//同步下载 正常模式是网页上点击下载,然后访问写的接口进行下载(超链接的方法不正规,因为浏览器能加载一些txt,word等文件)
@GetMapping("down")
public ResponseEntity download(String path,String realName,HttpServletRequest req){
String realPath = req.getServletContext().getRealPath("/");//先找到文件,获取根路径
String absPath = realPath+path;//得到绝对路径
byte[] bytes =null;
HttpHeaders headers = new HttpHeaders();
try {
bytes = FileUtils.readFileToByteArray(new File(absPath));//把一个文件读成一个数组
headers.add("Content-Disposition","attachment;filename="+URLEncoder.encode(realName,"UTF-8"));//文件下载响应头
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity(bytes,headers,HttpStatus.OK);
}
之前在下载的时候,一直找不到下载文件的路径,卡了很久。后来删掉了一层文件,就是把下载文件的路径从/upload/temp/xxx.txt修改为/upload/xxx.txt就能成功了,目前还不知道是什么原因,待以后修改