一. 文件上传
这里我们使用request.getSession().getServletContext().getRealPath("/static")的方式来设置文件的存储路径,并存入数据库中
request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径
这里我的文件就保存在了tomcat容器:C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.4580300150688111201.8080\static下
当我们部署到linux的时候,文件就保存在了/tmp/tomcat-docbase.6117940652560190565.8088/static/下
Controller:
/**
* 多文件上传接口
* */
@ResponseBody
@RequestMapping(value = "/fileUpload", produces = "application/json;charset=UTF-8")
public JSONObject fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception{
String serverName = "文件上传";
VirgoLog.updateStep(CONTROLLER_NAME_DES,serverName);
List<FileManage> fileManages = fileService.fileUpload(files,request);
Map<String,Object> resMap = new HashMap<String,Object>();
//0:操作成功
resMap.put("code", ErrorCode.ERR_SUCCEED.getErrorCode());
resMap.put("desc",ErrorCode.ERR_SUCCEED.getErrorMessage());
resMap.put("fileInfo",fileManages);
return JSON.parseObject(JSONConvertor.toJSON(resMap));
}
service 文件上传业务类
/**
* 文件上传service
* @param files
* @throws Exception
*/
@Override
public void fileUpload(@RequestParam("file")MultipartFile[] files, HttpServletRequest request) throws Exception {
//文件命名
//保存时的文件名
for(int i=0;i<files.length;i++) {
//保存文件到本地文件,并保存路径到数据库
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Calendar calendar = Calendar.getInstance();
String fileName = df.format(calendar.getTime()) + files[i].getOriginalFilename();
log.log("文件的文件名为:" + fileName);
//保存文件的绝对路径
String filePath = request.getSession().getServletContext().getRealPath("static/");
log.log("文件的绝对路径:" + filePath);
FileManage fileManage = new FileManage();
try {
//上传文件
FileUtil.uploadFile(files[i].getBytes(), filePath, fileName);
//保存到数据库代码,存入路径以及文件名称
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
throw new ZDYException(ErrorCode.ERR_FILE_UPLOAD_FAIL);
}
}
}
文件上传工具类
/**
* Created by hengyang4 on 2018/11/2.
*/
public class FileUtil { //文件上传工具类服务方法
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{ File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
} }
二. 文件下载
/**
* 文件下载service
* @param fileId
* @throws Exception
*/
@Override
public String downloadFile(String fileId, HttpServletResponse response) throws Exception {
//这里要根据文件id在数据库中查询之前保存的文件信息 FileManage fileManage = fileManageMapper.selectByPrimaryKey(fileId);
//文件名
String fileName = fileManage.getFileName();
//文件的相对路径
String path = fileManage.getFilePath();
InputStream inputStream = new FileInputStream(new File(path + fileName));
//如果文件不存在
if(inputStream == null){
throw new ZDYException(ErrorCode.ERR_NOT_FILE);
}
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
try {
String name = java.net.URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + name );
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(inputStream);
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (FileNotFoundException e1) {
//e1.getMessage()+"系统找不到指定的文件";
throw new ZDYException(ErrorCode.ERR_NOT_FILE);
}catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "success"; }
这就是springboot中文件的上传和下载,很简单很快捷