今天分享 spring boot单个和批量上传文件,这是系统的常用功能;
1、控制层代码展示:
1)单个上传:
/**
* 上传端口关系文件
* @param request
* @param file
* @param type
* @param groupId
* @RequestParam("file") MultipartFile file 此设置很重要,关系到上传时设置
* @return
*/
@RequestMapping("/uploadFile")
public void uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam("type") String type, @RequestParam("groupId") Integer groupId){
if( StringUtils.isEmpty(type) || Objects.isNull(groupId)){
throw LogicException.le("参数为空");
}
DocumentInfo documentInfo = new DocumentInfo();
documentInfo.setType(type);
documentInfo.setGroupId(groupId);
String fileName = file.getOriginalFilename();
String mimeType = request.getServletContext().getMimeType(fileName);
log.info("文件名称:{},和mimeType:",fileName,mimeType);
documentInfo.setName(fileName);
documentService.uploadFile(file,documentInfo);
//return null;
}
业务处理:
@Override
public void uploadFile(MultipartFile file, DocumentInfo documentInfo) {
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
// String mimeType = request.getServletContext().getMimeType(fileName);
String path = "";
String mimeType = "mimeType";
boolean isImage = false;
FileInputStream inputStream = null;
BufferedReader reader = null;
String line=null;
File dst = null;
try {
if (mimeType.startsWith("image/")) { // 图片
// It's an image.
// path = commonService.handleImage(uploadFiles, serialNo);
isImage = true;
} else {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateNowStr = sdf.format(date);
Calendar cal = Calendar.getInstance();
path = cal.get(Calendar.YEAR) + File.separator + dateNowStr + File.separator ;
// String host = GlobalConfigurationReader.getProperty("system.buildWordPath") + path;
String host = "E:\\power\\update\\" + path;//本地测试地址
// String host = fileDir + path;//正式环境地址
File wordDir = new File(host);//存到临时文件目录
if (!wordDir.exists()) {
wordDir.mkdirs();
}
// String pathName = UUID.randomUUID() + "." + prefix;
dst = new File(wordDir,fileName);
// File dst = new File(wordDir, pathName);//给文件换名称
// file.transferTo(dst); //暂时注释掉上传接口
// path = path + File.separator + pathName;
// path = path + File.separator + fileName;
path = path + fileName;
//String hostPath = path + fileName;
}
/**
* 上传保存到文件服务中:其实就是把文件专门保存在一个服务中
*/
RestResult restResult = uploadFileManageClient.serviceUpload(file, "订单文件", null);
log.info("返回加密文件地址:{};返回码:{};返回信息:{}",restResult.getData().toString(),restResult.getCode(),restResult.getMessage());
/**
* 文件内容存到数据库
*/
StringBuilder strFlie = new StringBuilder();
inputStream = new FileInputStream(dst);
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line=reader.readLine())!=null) {
strFlie.append(line);
}
log.info("文件内容:{}",strFlie.toString());//String.trim()
documentInfo.setContent(strFlie.toString().trim());
documentInfo.setName(fileName);
documentInfo.setPath(path);
documentInfoMapper.insert(documentInfo);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(null !=inputStream){
inputStream.close();
}
if(null !=reader){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
2)批量上传:和单个上传类似,只是传文件时时数组格式,控制层代码如下:
/**
* 批量上传关系文件
* @param request
* @param files
* @param type
* @param groupId
* @RequestParam("file") MultipartFile[] files 主要参数
* @return
*/
@RequestMapping("/batchUploadFile")
public void batchUploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] files, @RequestParam("type") String type, @RequestParam("groupId") Integer groupId){
if( StringUtils.isEmpty(type) || Objects.isNull(groupId)){
throw LogicException.le("参数为空");
}
DocumentInfo documentInfo = new DocumentInfo();
documentInfo.setType(type);
documentInfo.setGroupId(groupId);
for(MultipartFile flie : files){//循环单个上传
String fileName = flie.getOriginalFilename();
String mimeType = request.getServletContext().getMimeType(fileName);
log.info("文件名称:{},和mimeType:",fileName,mimeType);
documentInfo.setName(fileName);
documentService.uploadFile(flie,documentInfo);
}
}
业务层代码都一样。
3、postman测试上传:
4、单个下载:
控制层
/**
* 单个下载文件
* @param request
* @param response
* @param pid
* @return
*/
@RequestMapping("/downFileByFileKey")
public void downFileByFileKey(HttpServletRequest request, HttpServletResponse response,
@RequestParam("pid") Integer pid){
if( Objects.isNull(pid)){
throw LogicException.le("参数为空");
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
downloadService.downloadFileByFileKey(request,pid,response,bis,bos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
业务层:
@Override
public void downloaFileByFileKey(HttpServletRequest request, Integer pid, HttpServletResponse response, BufferedInputStream bis, BufferedOutputStream bos) throws Exception {
DocumentInfo documentInfo = documentInfoMapper.selectByPrimaryKey(pid);
String fileKey = documentInfo.getFileKey();
if(StringUtils.isEmpty(fileKey)){
throw new NullPointerException("文件索引id为空");
}
Response resultResponse = dssFileManageClient.serviceDownload(fileKey);
log.info("取到的文件信息:{}",resultResponse.body());
// String prefix = "";
String fileName = documentInfo.getName();//文件名称
String agent = request.getHeader("User-Agent").toLowerCase();
boolean isMSIE = (agent != null && (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1)));
if (isMSIE) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=\""+ fileName+"\"");
/* if(StringUtils.isNotBlank(suffix) && Objects.equals("pdf",suffix.toLowerCase())){
response.setContentType("application/pdf;charset=GBK");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "inline;filename="+ imageRealName);
}else{
response.setContentType("image/jpg");
}*/
bis = new BufferedInputStream(resultResponse.body().asInputStream());
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bos.flush();
log.info("下载文件成功:{}",fileName);
}
客户端下载测试:成功下载
这就是单个下载文件的分享,多个下载也是同理。
上传和下载分享完毕,此方案不仅适合springboot 还适用 springMVC或Struts框架!