目录

前言

功能介绍

实现

依赖

配置

Controller

效果-单文件

效果-多文件


前言

上传文件功能是每个项目必备的功能,通过多个项目不断升级而来,在实现相同效果的情况下,代码越来越简化。

代码中用到了hutool工具库,这个库确实比较强大,可以轻松解决很多问题。hutool官网api文档https://apidoc.gitee.com/dromara/hutool/

hutool官网https://hutool.cn/docs/#/

在拿到项目需求时,先以最快的速度完成需求,然后逐渐完善代码,完善的代码将用于下一个项目。

所有的项目,我们都遵守拿来即用原则。

功能介绍

单文件上传,多文件上传,wangedit富文本上传(大同小异,只是返回格式不同)

fileRootPath:是文件放置的父级路径,比如:lunbotu(轮播图),user/headimg(用户头像),user/photo(用户相册),videos(视频),等等,支持多级路径。

实现

依赖

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.1</version>
</dependency>

配置

server:servlet:context-path: /tmpl#上传文件配置
upload:
#  保存文件路径path: D:/yanwei/projects/yanwei/files
#  访问url路径,/tmpl为前缀webbasepath: http://127.0.0.1:8080/tmpl/file
package com.yanwei.tmpl.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @Author 闫伟* @DATE 2021/9/20 17:23* @Description:*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Value("${upload.path}")private String uploadPath = "";@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/file/**").addResourceLocations("file:" + uploadPath + "\\");}
}

Controller

package com.yanwei.tmpl.module.common.file;import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.yanwei.tmpl.module.common.jpa.utils.Result;
import com.yanwei.tmpl.module.common.jpa.utils.ResultUtil;
import com.yanwei.tmpl.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Value;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;/*** 文件*/
@RestController
@RequestMapping("/api/com/file")
public class FileUpController {@Value("${upload.path}")private String uploadPath;@Value("${upload.webbasepath}")private String webbasepath;/*** 单个文件** @param file* @return*/@PostMapping(value = "/up")public Result up(@RequestParam("file") MultipartFile file, String fileRootPath) throws IOException {if(!file.isEmpty()){return ResultUtil.data(saveFile(file,fileRootPath));}return ResultUtil.data(getResult("","",""));}/*** 多文件** @param files* @return*/@PostMapping(value = "/ups")public Result ups(@RequestParam("files") MultipartFile[] files, String fileRootPath) throws IOException {if(files.length > 0){List<Map<String,String>> list = ListUtil.toList();for (MultipartFile multipartFile : files) {list.add(saveFile(multipartFile,fileRootPath));}return ResultUtil.data(list);}return ResultUtil.data(getResult("","",""));}/*** WangEdit富文本编辑器文件上传** {*     "errno": 0, // 注意:值是数字,不能是字符串.0:成功;1:失败*     "data": {*         "url": "xxx", // 图片 src ,必须*         "alt": "yyy", // 图片描述文字,非必须*         "href": "zzz" // 图片的链接,非必须*     },*     "message": "失败信息"* }* @param file* @return*/@PostMapping(value = "/upWidthWangEdit")public Object upWidthWangEdit(@RequestParam("file") MultipartFile file, String fileRootPath, HttpServletRequest httpServletRequest) throws IOException {Map map = MapUtil.newHashMap();if(!file.isEmpty()){Map<String,String> saveFileResult = saveFile(file,fileRootPath);map.put("errno",0);map.put("data",saveFileResult);}else{map.put("errno",1);map.put("message","上传失败,请重新上传");}return map;}/*** 保存文件到本地* @param multipartFile* @param fileRootPath* @return* @throws IOException*/private Map<String,String> saveFile(MultipartFile multipartFile, String fileRootPath) throws IOException {String fileName = multipartFile.getOriginalFilename();//新文件名String newFileName = String.format("%s.%s", IdUtil.simpleUUID(), FileUtil.getSuffix(fileName));//相对路径和绝对路径String newRelativePath = String.format("%s/%s", fileRootPath, newFileName);String realPath = String.format("%s/%s", uploadPath, newRelativePath);//创建文件夹cn.hutool.core.io.FileUtil.mkParentDirs(realPath);//保存文件到本地multipartFile.transferTo(new File(realPath));return getResult(newFileName,newRelativePath,String.format("%s/%s", webbasepath, newRelativePath));}/*** 上传文件结果* @param name* @param path* @param url* @return*/private Map<String,String> getResult(String name,String path,String url){Map<String,String> result = MapUtil.newHashMap();result.put("name",name);//文件名result.put("path",path);//相对路径result.put("url",url);//绝对路径return result;}
}

效果-单文件

效果-多文件

实现文件上传,从配置到上传文件到获取文件相关推荐

  1. 【文件md5值查看方法详解】:如何获取文件的唯一标识?

    [文件md5值查看方法详解]:如何获取文件的唯一标识? 在日常工作中,我们经常需要检查文件是否被篡改或者验证文件的完整性.而文件的MD5值就是一个很好的选择,因为它可以作为文件的唯一标识.那么,如何获 ...

  2. Antd的Upload组件上传文件控制文件数量、格式等,以及提交时如何获取文件

    背景:使用React的antd组件的Upload(官网),要求文件上传后,在点击提交时再将文件传过去. 技术点: 完全控制的文件上传. 可控制上传数量. 控制文件格式. 移除时的事件onRemove. ...

  3. Linux查看文件字节数、行数、大小【shell获取文件行数、字节数】

    wc xxx.dat wc xxx.dat:使用wc可以查看文件的信息,信息内容对应的分别是 行数 单词数 字节数 文件名 使用awk可以获取对应的值: wc xxx.dat |awk '{print ...

  4. Python计算校验文件的MD5、SHA1、SHA256和CRC32,获取文件创建日期、修改日期和文件大小

    main.py # -*- coding: utf-8 -*- import os from hashlib import md5, sha1, sha256 from zlib import crc ...

  5. java fileupload 进度_SpringBoot+fileUpload获取文件上传进度

    我本人在网上找了很多关于文件上传进度获取的文章,普遍基于spring MVC 框架通过 fileUpload 实现,对于spring Boot 通过 fileUpload 实现的帖子非常少,由于小弟学 ...

  6. 文件上传:避免重复上传

    上一篇文章说了,使用 SparkMd5 来获取文件 md5 的 Hash 标识来判断是否已经上传过了,现在代码实现一下 (一)安装 在项目中安装 spark-md5 cnpm i spark-md5 ...

  7. 利用计算机网线传东西,如何把文件通过一个网线从一个电脑传到另一个电脑上...

    满意答案 bbwan1109 推荐于 2017.09.29 采纳率:40%    等级:5 已帮助:157人 根据你所说的情况,你不能(没有硬件条件)组成一个局域网. 不过你可以用一根直通线,连接到两 ...

  8. pycharm python 模板配置_windows下pycharm安装、创建文件、配置默认模板

    本文为大家分享了windows下pycharm安装.创建文件.配置默认模板的具体步骤,供大家参考,具体内容如下 步骤: 下包 -->安装-->创建文件-->定制模板 一.下包 官方地 ...

  9. python 如何获取文件路径_Python如何获取文件路径/目录

    一.获取文件路径实现 1.1 获取当前文件路径 import os current_file_path = __file__ print(f"current_file_path: {curr ...

  10. ios 从服务器获取文件,ios - 如何将远程文件(从远程SMB服务器获取)提供给某些请求 - 堆栈内存溢出...

    当某些请求命中服务器(在移动应用程序上运行的服务器)时,我正在尝试将视频文件作为响应提供. 该视频文件可以存储在本地,也可以是外部存储的. 我开始尝试提供位于SMB服务器上的文件,所以我尝试使用此代码 ...

最新文章

  1. 2021-2027年中国智能门禁系统市场研究及前瞻分析报告
  2. java 无符号转有符号_java有符号无符号的转换
  3. LeetCode Sort List(单链表归并排序)
  4. Q767 重构字符串
  5. 有三AI知识星球官宣,BAT等大咖等你来撩
  6. SSH项目中遇到拦截器无法注入服务的问题
  7. Android 封装handler,android封装工作线程跟Handler工具类
  8. [Unity][NodeCanvas] 点击场景中的游戏对象以观察行为树运行情况
  9. Win7系统忘记登入密码的解决方法
  10. 任性!特斯拉又涨价了 Model S、Model X国内售价上调
  11. SAP License:SAP不便解决的问题之五——客供料
  12. 在TensorFlow中实现文本分类的卷积神经网络
  13. Quartz配置信息
  14. 综合布线系统技术是建设智慧城市的血脉
  15. 爬取汽车之家所有车型,价格,配置
  16. Python 实验二 tkinter 版小学数学口算题生成器设计与实现
  17. 设计模式——软件设计的太极剑法
  18. MBD(一)-下载包-getstart-raspberry串口设置问题
  19. CTFshow-原谅杯(1-4)
  20. AI人工智能入门(浅析AlphaGo的实现)

热门文章

  1. 安全与隐私计算在国内发展现状
  2. Oracle11g数据库创建表的方式——Sqlplus命令和企业管理器
  3. 【图像隐写】基于matlab DWT+FFT+DCT水印攻击+提取【含Matlab源码 2411期】
  4. HTTP协议之头字段简介
  5. python语言基础笔记_python语言学习笔记整理
  6. iOS/APP/苹果超级企业签名是什么原理
  7. 创维G60 显示器参数 创维G60 显示器 评测怎么样
  8. 树莓派桌面任务栏 LXPanel 不小心删除恢复的教程
  9. 计算机专业毕业生在个人简历上计算机水平怎么写,计算机个人简历范文_非计算机专业毕业生在个人简历上“计算机水平”怎么写...
  10. java 获取长度为5的随机字符串,字符串由随机的5个大小写字母组成