springmvc文件上传、下载(文件储存到当前服务器)

您所在的位置:网站首页 springmvc文件上传大小 springmvc文件上传、下载(文件储存到当前服务器)

springmvc文件上传、下载(文件储存到当前服务器)

2024-01-07 01:22| 来源: 网络整理| 查看: 265

一、场景

最新需要做个小项目,比较简单的一个网站,就用到了mysql和redis,系统中有文件管理功能;这里就简单实现,储存到当前服务器即可。

二、controller代码实现 package com.xiangpeng.common.file; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.xiangpeng.base.exception.BaseException; import com.xiangpeng.base.response.JsonResult; import com.xiangpeng.base.util.IoUtils; import com.xiangpeng.base.util.ResponseUtils; import com.xiangpeng.common.controller.BaseController; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @Api(tags = "文件管理") @RestController @RequestMapping("file") public class FileController extends BaseController { @Value("${file.folder.path:''}") private String fileFolderPath; @ApiOperation("上传") @PostMapping(value = "/v1/upload") public JsonResult upload(HttpServletRequest request, MultipartFile file) throws IOException { if (null == file) { return JsonResult.error(BaseException.UPLOAD_FAILED, messageSource); } if (file.getSize() >= 20 * 1024 * 1024) { return JsonResult.error(BaseException.UPLOAD_FAILED, messageSource); } String filePath = fileFolderPath + LocalDate.now().toString() + "/" + file.getOriginalFilename(); FileUtils.writeByteArrayToFile(new File(filePath), file.getBytes()); Map map = new HashMap(); map.put("name", file.getOriginalFilename()); map.put("path", filePath); return new JsonResult().success(map); } @ApiOperation("下载") @GetMapping(value = "/v1/download") public void download(HttpServletResponse response, @ApiParam(value = "文件路径") @RequestParam("path") String path) throws IOException { if (StrUtil.isBlank(path)) { ResponseUtils.printMessage(response, "file path can not be empty."); return; } if (!FileUtil.isFile(path)) { ResponseUtils.printMessage(response, "this file no exists."); return; } byte[] fileBytes = FileUtils.readFileToByteArray(new File(path)); IoUtils.outputFile(response, path.substring(path.lastIndexOf("/") + 1), fileBytes); } }

其中文件存放的目录从配置文件中读取,文件按日期创建文件夹存放;下载用到如下方法:

public static void outputFile(HttpServletResponse response, String fileName, byte[] file) throws UnsupportedEncodingException { if (ArrayUtils.isEmpty(file)) { LOGGER.info("get file download url failed."); return; } // 设置相关头信息 response.setContentType("multipart/form-data"); fileName = StringUtils.isNotEmpty(fileName) ? fileName : UUID.randomUUID().toString(); // fileName = new String(fileName.getBytes("iso-8859-1"), Constants.UTF8); // 文件名编码 try { fileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("fileName encode failed. errorMessage[{}]", e.getMessage()); } response.setHeader("Content-disposition", "attachment;filename=" + fileName); response.addHeader("Pragma", "no-cache"); response.addHeader("Cache-Control", "no-cache"); response.addDateHeader("Expries", 0); // 返回文件 OutputStream out = null; try { out = response.getOutputStream(); out.write(file); out.flush(); } catch (IOException e) { LOGGER.error("download file failed. errorMessage[{}]", e.getMessage()); } finally { if (null != out) { try { out.close(); } catch (IOException e) { LOGGER.error("OutputStream close failed. errorMessage[{}]", e.getMessage()); } } } }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3