目录

单文件上传篇

1、html

2、JS

3、Controller

3.1 Global.getProfile()

3.3.1 JarBasePath.getBaseJarPathStr()

3.2  FileUploadUtils.upload(filePath, file)   --ruoyi框架自带的

4、Service 和 Xml 就不写了 没什么价值

多文件打包下载压缩包篇

1、html

2、JS

3、Controller

4、Config --配置文件上传下载本地位置的(搞得我也是昏头转向的)

5、Service 和 xml 就不写了,没什么价值


单文件上传篇

1、html

<!--    注意,这个文件的上传和下载功能一定要放在一个form里方便处理--><form class="form-horizontal m" id="form-checkCarPhoto-show" th:object="${CarPhoto}"><input id="id" name="id" th:field="*{id}"  type="hidden">
<!--      单文件上传按钮--><input id="filePath" name="filePath" class="form-control" type="file"><a class="btn btn-success btn-xs " href="#" onclick="uploadFile()"><i class="fa fa-edit"></i>单文件上传</a>
<!--      多文件打包下载按钮--><a class="btn btn-success btn-xs " href="#" onclick="downloadFile($('#id').val())"><i class="fa fa-edit"></i>全部下载</a></form>

2、JS

 function uploadFile() {var formData = new FormData();  //定义上传文件if ($('#filePath')[0].files[0] == null) { //判断文件是否为空$.modal.alertWarning("请先选择文件路径");return false;}formData.append('fileName', $("#fileName").val());  //放入文件名formData.append('file', $('#filePath')[0].files[0]);  //放入文件地址$.ajax({url: prefix + "/add/"+$('#id').val() ,  //controller文件映射,依据自己定义的写type: 'post',cache: false,data: formData,processData: false,     //Jquery是否会序列化数据//contentType:发送信息至服务器时内容编码类型(告诉服务器从浏览器提交过来的数据格式)// 默认值为contentType = "application/x-www-form-urlencoded"// 在 ajax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件。contentType: false,dataType: "json",success: function(result) {$.operate.successCallback(result);}});}

3、Controller

 @PostMapping("/add/{cid}")@ResponseBodypublic AjaxResult addSave(@PathVariable("cid") Integer cid, @RequestParam("file") MultipartFile file, FileInfo fileInfo) throws IOException{// 上传文件路径String filePath = Global.getProfile() + "check/";// 上传并返回新文件名称String fileName = FileUploadUtils.upload(filePath, file);CarPhoto carPhoto = new CarPhoto();carPhoto.setPhotoUrl(fileName);carPhoto.setCheckId(cid);// 插入数据并返回结果至前端return toAjax(carPhotoService.insertCarPhoto(carPhoto));}

3.1 Global.getProfile()

package com.bloodmanage.common.config;import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;import com.bloodmanage.common.utils.http.JarBasePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bloodmanage.common.utils.StringUtils;
import com.bloodmanage.common.utils.YamlUtil;/*** 全局配置类* * @author songzihao*/
public class Global
{private static final Logger log = LoggerFactory.getLogger(Global.class);private static JarBasePath jarBasePath = new JarBasePath();private static String NAME = "application.yml";/*** 当前对象实例*/private static Global global = null;/*** 保存全局属性值*/private static Map<String, String> map = new HashMap<String, String>();private Global(){}/*** 静态工厂方法 获取当前对象实例 多线程安全单例模式(使用双重同步锁)*/public static synchronized Global getInstance(){if (global == null){synchronized (Global.class){if (global == null)global = new Global();}}return global;}/*** 获取配置*/public static String getConfig(String key){String value = map.get(key);if (value == null){Map<?, ?> yamlMap = null;try{yamlMap = YamlUtil.loadYaml(NAME);value = String.valueOf(YamlUtil.getProperty(yamlMap, key));map.put(key, value != null ? value : StringUtils.EMPTY);}catch (FileNotFoundException e){log.error("获取全局配置异常 {}", key);}}return value;}/*** 获取文件上传路径*/public static String getProfile(){//return getAbsolute() + File.separator + getConfig("blood.profile");return jarBasePath.getBaseJarPathStr();}/*** 获取头像上传路径*/public static String getAvatarPath(){//String path = getAbsolute() + File.separator + getConfig("blood.profile") + File.separator + "avatar/";//return path;return jarBasePath.getBaseJarPathStr() + "avatar/";}/*** 获取下载上传路径*/public static String getDownloadPath(){//return getAbsolute() + File.separator + getConfig("blood.profile") + File.separator + "download/";//return getConfig("blood.profile") + "download/";return jarBasePath.getBaseJarPathStr()+"download/";}/*** 获取jar包的目录* @return*/private static String getAbsolute() {String jarWholePath = Global.class.getProtectionDomain().getCodeSource().getLocation().getFile();try {jarWholePath = java.net.URLDecoder.decode(jarWholePath, "UTF-8");} catch (UnsupportedEncodingException e) { System.out.println(e.toString()); }String jarPath = new File(jarWholePath).getParentFile().getAbsolutePath();jarPath = jarPath.substring(0, jarPath.indexOf("bloodmanage"));return jarPath;}
}

3.3.1 JarBasePath.getBaseJarPathStr()

public class JarBasePath {private static final Logger log = LoggerFactory.getLogger(JarBasePath.class);/*** 获取当前jar包所在系统中的目录*/public File getBaseJarPath() {ApplicationHome home = new ApplicationHome(getClass());File jarFile = home.getSource();return jarFile.getParentFile();}public String getBaseJarPathStr() {File file = getBaseJarPath();return file.getAbsolutePath().toLowerCase().trim() + "/";}
}

3.2  FileUploadUtils.upload(filePath, file)   --ruoyi框架自带的

package com.bloodmanage.framework.util;import java.io.File;
import java.io.IOException;
import org.apache.tomcat.util.http.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.springframework.web.multipart.MultipartFile;
import com.bloodmanage.common.config.Global;
import com.bloodmanage.common.exception.file.FileNameLengthLimitExceededException;
import com.bloodmanage.common.utils.Md5Utils;/*** 文件上传工具类* * @author xing*/
public class FileUploadUtils
{/*** 默认大小 50M*/public static final long DEFAULT_MAX_SIZE = 52428800;/*** 默认上传的地址*/private static String defaultBaseDir = Global.getProfile();/*** 默认的文件名最大长度*/public static final int DEFAULT_FILE_NAME_LENGTH = 200;/*** 默认文件类型jpg*/public static final String IMAGE_JPG_EXTENSION = ".jpg";private static int counter = 0;public static void setDefaultBaseDir(String defaultBaseDir){FileUploadUtils.defaultBaseDir = defaultBaseDir;}public static String getDefaultBaseDir(){return defaultBaseDir;}/*** 以默认配置进行文件上传** @param file 上传的文件* @return 文件名称* @throws Exception*/public static final String upload(MultipartFile file) throws IOException{try{return upload(getDefaultBaseDir(), file, FileUploadUtils.IMAGE_JPG_EXTENSION);}catch (Exception e){throw new IOException(e);}}/*** 根据文件路径上传** @param baseDir 相对应用的基目录* @param file 上传的文件* @return 文件名称* @throws IOException*/public static final String upload(String baseDir, MultipartFile file) throws IOException{try{return upload(baseDir, file, FileUploadUtils.IMAGE_JPG_EXTENSION);}catch (Exception e){throw new IOException(e);}}/*** 文件上传** @param baseDir 相对应用的基目录* @param file 上传的文件* @param needDatePathAndRandomName 是否需要日期目录和随机文件名前缀* @param extension 上传文件类型* @return 返回上传成功的文件名* @throws FileSizeLimitExceededException 如果超出最大大小* @throws FileNameLengthLimitExceededException 文件名太长* @throws IOException 比如读写文件出错时*/public static final String upload(String baseDir, MultipartFile file, String extension)throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException{int fileNamelength = file.getOriginalFilename().length();if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH){throw new FileNameLengthLimitExceededException(file.getOriginalFilename(), fileNamelength,FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);}assertAllowed(file);String fileName = encodingFilename(file.getOriginalFilename(), extension);File desc = getAbsoluteFile(baseDir, baseDir + fileName);file.transferTo(desc);return fileName;}private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException{File desc = new File(File.separator + filename);if (!desc.getParentFile().exists()){desc.getParentFile().mkdirs();}if (!desc.exists()){desc.createNewFile();}return desc;}/*** 编码文件名*/private static final String encodingFilename(String filename, String extension){filename = filename.replace("_", " ");filename = Md5Utils.hash(filename + System.nanoTime() + counter++) + extension;return filename;}/*** 文件大小校验** @param file 上传的文件* @return* @throws FileSizeLimitExceededException 如果超出最大大小*/public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException{long size = file.getSize();if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE){throw new FileSizeLimitExceededException("not allowed upload upload", size, DEFAULT_MAX_SIZE);}}
}

4、Service 和 Xml 就不写了 没什么价值

多文件打包下载压缩包篇

1、html

<!--    注意,这个文件的上传和下载功能一定要放在一个form里方便处理--><form class="form-horizontal m" id="form-checkCarPhoto-show" th:object="${CarPhoto}"><input id="id" name="id" th:field="*{id}"  type="hidden">
<!--      单文件上传按钮--><input id="filePath" name="filePath" class="form-control" type="file"><a class="btn btn-success btn-xs " href="#" onclick="uploadFile()"><i class="fa fa-edit"></i>单文件上传</a>
<!--      多文件打包下载按钮--><a class="btn btn-success btn-xs " href="#" onclick="downloadFile($('#id').val())"><i class="fa fa-edit"></i>全部下载</a></form>

2、JS

  function downloadFile(value){window.location.href = prefix + "/resource?id=" + value;}

3、Controller

注意:集合判断是否为空isEmpty()与==null的区别 可以使用的两种办法:

一:if(list!=null&&!list.isEmpty())

二:CollectionUtils.isEmpty()

详情可以看文章:集合判断是否为空isEmpty()与==null的区别_唯空城的博客-CSDN博客_isempty和==null

 /*** 本地资源通用下载*/@GetMapping("/resource")@ResponseBodypublic void resourceDownload(Integer id, HttpServletRequest request, HttpServletResponse response)throws Exception{// 用id查照片列表List<CarPhoto> photos = carPhotoService.selectCarPhotoListByCid(id);//判断照片列表是否为空,注意:这样两种判断是为了避免空指针异常if(photos == null || photos.isEmpty()){throw new ServiceException("0", "此条车检信息没有照片可以下载!");}// 用id查车检信息CarCheck carCheck = carCheckService.selectCarCheckById(id);DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");// 时间格式化String strdate = dateformat.format(carCheck.getCreateTime());// 压缩包名字拼一拼String zipName = carCheck.getDriverName() + '_'+ carCheck.getCarStr() + '_'+ strdate + '_'+ "车检照片.zip";// 下面就是百度搜来的压缩包操作了ZipOutputStream zos = null;response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName, "UTF-8"));zos = new ZipOutputStream(response.getOutputStream());downloadTolocal(zos, photos);}/*** 本地资源压缩为zip*/private void downloadTolocal(ZipOutputStream zos, List<CarPhoto> photos) throws IOException {InputStream input = null;// 本地资源路径String localPath = Global.getProfile() + "check/";String downloadPath = "";for (CarPhoto photo : photos) {downloadPath = localPath + photo.getPhotoUrl();File file = new File(downloadPath);// 一个文件对应一个ZipEntryZipEntry zipEntry = new ZipEntry(file.getName());input = new FileInputStream(file);zos.putNextEntry(zipEntry);IOUtils.copy(input, zos);}zos.close();input.close();}

4、Config --配置文件上传下载本地位置的(搞得我也是昏头转向的)

package com.bloodmanage.framework.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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.bloodmanage.common.config.Global;/*** 通用配置* * @author xing*/
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{/*** 首页地址*/@Value("${shiro.user.indexUrl}")private String indexUrl;/*** 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页*/@Overridepublic void addViewControllers(ViewControllerRegistry registry){registry.addViewController("/").setViewName("forward:" + indexUrl);}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){/** 文件上传路径 */registry.addResourceHandler("/profile/**").addResourceLocations("file:///" + Global.getAvatarPath());registry.addResourceHandler("/check/**").addResourceLocations("file:///" + Global.getProfile() + "check/");/** swagger配置 */registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}
}

5、Service 和 xml 就不写了,没什么价值

Ruoyi实现单文件上传和多文件打包压缩包下载相关推荐

  1. SpringMVC 单文件上传与多文件上传

    一.简述 一个javaWeb项目中,文件上传功能几乎是必不可少的,本人在项目开发中也时常会遇到,以前也没怎么去理它,今天有空学习了一下这方面的知识,于是便将本人学到的SpringMVC中单文件与多文件 ...

  2. springboot文件上传,单文件上传和多文件上传,以及数据遍历和回显

    springboot文件上传,单文件上传和多文件上传 项目结构及pom.xml 创建文件表单页面 编写javabean 编写controller映射 MultipartFile类 @RequestPa ...

  3. Dropzone单文件上传、多文件上传、文件夹上传,springmvc接收,上传至Minio的一系列问题

    0 前言 1.项目需要上传文件和大量的文件夹,页面只有一个input file标签会很丑,偶然间得知dropzone类库, 决定使用. 2. 项目后端采用springmvc接收,调用minio代码上传 ...

  4. 文件上传 java web_JavaWeb 文件上传下载

    1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端,从服务器端下载文件到本地的过程.例如目前网站需要上传头像.上传下载图片或网盘等功能都是利用文件上传下 ...

  5. ***使用PHP实现文件上传和多文件上传

    http://www.365mini.com/page/php-upload-file.htm 在PHP程序开发中,文件上传是一个使用非常普遍的功能,也是PHP程序员的必备技能之一.值得高兴的是,在P ...

  6. 多文件上传,大文件上传3、5个G,那都不是事

    一套大文件上传的教程给大家. https://www.yyjcw.com/html/ke/34.html 重点讲解了多文件上传,大文件上传,分块上传,断点续传,文件秒传,上传失败自动修复再上传等功能, ...

  7. SSM框架使用Layui文件上传插件实现多文件上传(多文件列表)

    SSM框架使用Layui文件上传插件实现多文件上传(多文件列表) pom.xml文件的配置 想要实现SSM框架实现多文件上传,必要的jar包必须要在pom.xml文件中引入.如下: <!--co ...

  8. layui实现文件压缩上传_基于SSM框架、Layui的多文件上传、包括图片,压缩包,音频等文件(与数据库挂钩) - 爱秧博客...

    写在前面:当初为了实现一个多文件上传可是费了一番功夫,经过我日日夜夜的百度咨询,写了好几种方法,最终还是没能解决问题.我可以很负责任的告诉你,你去百度上不管你形容有多好,只要是涉及多文件,就会查到Mu ...

  9. 文件上传时判断文件夹是否存在

    文件上传时判断文件夹是否存在 if($path!=''){ $path = C('UPLOAD_IMAGE_PATH').$path.'/';//上传路径 }else{ $path = C('UPLO ...

最新文章

  1. AI当红娘,真的能帮你摆脱单身吗?
  2. 动态规划算法解最长公共子序列LCS问题
  3. mybatis-spring 项目简介
  4. 蓝桥杯练习系统习题-算法提高1
  5. 三个打印函数printf()/sprintf()/snprintf()区别
  6. mysql header files_编译安装php Cannot find MySQL header files under /usr/include/mysql.
  7. Doctrine官方手册 - 缓存
  8. Ubuntu上安装Maven3
  9. sqlserver2000与sqlserver2005驱动与url的区别
  10. 迭代器适配器{(插入迭代器back_insert_iterator)、IO流迭代器(istream_iterator、ostream_iterator)}...
  11. java初学总结_Java初学总结
  12. Java EE服务技术
  13. Centos7 firewall防火墙常用配置
  14. 药物临床试验数据递交FDA的规定
  15. 八数码java_八数码问题-A*算法-Java实现
  16. Linux服务器下安装ANSYS
  17. ipcs中的dest是什么意思
  18. SMP、NUMA、MMP的简介
  19. matlab图源代码,[转载]常用的一些图像处理Matlab源代码
  20. Android自定义控件----继承ViewGroup侧滑菜单5,抽屉式侧滑,QQ5.0效果(完结)

热门文章

  1. 信号与系统学习笔记(1)
  2. python 获取 精确的13位时间戳 以及使用datetime 获取时间间隔
  3. python字符串‘’ “ ”使用以及使用转义字符
  4. 星速配资:周期股调整大消费反弹 行情风格要切换?
  5. 物理卷操作命令:pvcreate,pvscan,pvdisplay.卷组操作命令:vgcreate,vgdisplay. (转)
  6. proto3 协议指引
  7. 神经网络中的降维和升维方法 (tensorflow pytorch)
  8. 完美解决jasperreports集成ssh后生成HTML图片红叉叉问题和chart不能显示问题
  9. python猜数字小游戏(内附完整源码)
  10. 更轻量级的可视化引擎库