第一次接触ruoyi框架,碰到文件上传和下载问题,今天来总结一下。
使用若依框架文件上传下载首先配置文件路径要配好。
文件下载:
application.yml若依配置
# 项目相关配置
ruoyi:# 名称name: RuoYi# 版本version: 3.6.0# 版权年份copyrightYear: 2021# 实例演示开关demoEnabled: true# 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)# profile: /home/admin2409/fn/uploadPathprofile: D:/.code/uploadPath# 获取ip地址开关addressEnabled: false# 验证码类型 math 数组计算 char 字符验证captchaType: math
首先是文件下载,在若依框架下载上传文件工具已经写好了
页面:
前端方法:`
// 通用下载方法
export function download(fileName) {window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
}
后端通用方法:
单独写一个下载啊文件的请求
@GetMapping("/downloadTemplate")public AjaxResult importTemplate() throws IOException {return AjaxResult.success("hnxTemplate.xlsx");}
/*** 通用下载请求** @param fileName 文件名称* @param delete 是否删除*/@GetMapping("common/download")public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {try {if (!FileUtils.checkAllowDownload(fileName)) {throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 " , fileName));}String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);String filePath = RuoYiConfig.getDownloadPath() + fileName; //注意这里的路径要和你下载的路径对应response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);FileUtils.setAttachmentResponseHeader(response, realFileName);FileUtils.writeBytes(filePath, response.getOutputStream());if (delete) {FileUtils.deleteFile(filePath);}} catch (Exception e) {log.error("下载文件失败" , e);}}
RuoYiConfig.getDownloadPath()如果和你的路径不一样,改成一样的
/*** 获取下载路径*/public static String getDownloadPath() {return getProfile() + "/download/";}
这样就文件就可以下载了
文件上传:
application.yml同样的路径配置不变
页面:
前端代码:
<el-form-item label="场景图片:" prop="sceneImgurl"><el-uploadaction=""ref="uploadImport":http-request="httpRequest"list-type="picture-card":limit="1":file-list="fileList"accept=".jpg, .jpeg, .png, .gif":auto-upload="false":before-remove="removeImg"><i class="el-icon-plus"></i></el-upload></el-form-item>
httpRequest(param) {let params = new FormData();params.append('avatarfile', param.file); // 传文件uploadPlanImg(params).then(res => {if(res.code!==200) returnthis.form.sceneImgurl = res.imgUrl}); },
后端上传代码
/*** 上传平面图*/@Log(title = "上传平面图" , businessType = BusinessType.UPDATE)@PostMapping("/uplaodImg")public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {if (!file.isEmpty()) {String url= RuoYiConfig.getUploadPath();//配置自己的路径String avatar = FileUploadUtils.upload(url, file);AjaxResult ajax = AjaxResult.success();ajax.put("imgUrl" , avatar);return ajax;}return AjaxResult.error("上传图片异常,请联系管理员");}
String url= RuoYiConfig.getUploadPath();//配置自己的路径
/*** 获取上传路径*/public static String getUploadPath() {return getProfile() + "/upload";}
上传成功: