当前位置: 首页 > news >正文

SpringMVC文件上传、文件下载多文件上传及jrebel的使用与配置

一.文件上传

1.导入依赖

<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version>
</dependency>

2.配置文件上传解析器

在spring-mvc.xml文件中添加文件上传解析器。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --><property name="defaultEncoding" value="UTF-8"></property><!-- 文件最大大小(字节) 1024*1024*50=50M--><property name="maxUploadSize" value="52428800"></property><!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--><property name="resolveLazily" value="true"/>
</bean>

CommonsMultipartResolverMultipartResolver接口的实现类。

MultipartResolver是用于处理文件上传,当收到请求时DispatcherServletcheckMultipart()方法会调用MultipartResolverisMultipart()方法判断请求中是否包含文件,如果请求数据中包含文件,则调用MultipartResolverresolverMultipart()方法对请求的数据进行解析,然后将文件数据解析MultipartFile并封装在MultipartHTTPServletRequest(继承了HTTPServletRequest)对象中,最后传递给Controller

3.配置服务器存放文件地址

3.1. 

3.2 将项目部署到服务器上

 3.3 配置相应路径

3.4 选择我们control层的方法中定义的路径

 

 3.5 最后保存好即可

4.导入PropertiesUtil工具类

1.通过PropertiesUtil工具类加载配置页目录文件

package com.YU.utils;import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;public class PropertiesUtil {public static String getValue(String key) throws IOException {Properties p = new Properties();InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");p.load(in);return p.getProperty(key);}}

2.同时在代码中我们可以发现,通过工具类读取resource.properties文件,在配置文件resource.properties中,我们将一些服务器存放文件地址定义在该文件中,方便我们后期修改配置文件

3.resource.properties文件

dir = D:/deposit/upload/
server = /upload/

5.编写Controller层

 通过Controller层利用MultipartFile类接收前端传递的文件到后台,以流的方式上传到服务器中,

并将数据库中数据的字段(图片路径)进行修改

//文件上传@RequestMapping("/upload")public String upload(HBook hBook,MultipartFile bfile){try {String dir = PropertiesUtil.getValue("dir");String server = PropertiesUtil.getValue("server");String filename = bfile.getOriginalFilename();FileUtils.copyInputStreamToFile(bfile.getInputStream(), new File(dir + filename));hBook.setImg(server+filename);hBookbiz.updateByPrimaryKeySelective(hBook);} catch (IOException e) {e.printStackTrace();}return "redirect:list";}

6.编写前端页面

编写前端页面表单,通过post请求的方式将图片上传到服务器,并将数据进行修改

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>图片上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/book/upload" method="post" enctype="multipart/form-data"><label>书籍编号:</label><input type="text" name="bid" readonly="readonly" value="${param.bid}"/><br/><label>书籍图片:</label><input type="file" name="bfile"/><br/><input type="submit" value="上传图片"/>
</form></body>
</html>

注意:表单的提交方式为enctype="multipart/form-data" ,它是一个HTML表单属性,用于指定将表单数据编码为多部分(multipart)的格式,以便支持文件上传,文件上传需要额外的服务器端处理逻辑,包括文件存储、验证、处理等。在服务器端代码中,需要根据我们的需求来处理上传的文件

7.测试结果

我们在将数据传输到服务器时,可以通过查看服务器部署的地址查看我们传输的文件

 

 二.文件下载

我们通过controller层调用请求方法,获取到服务器本地请求地址,并将网络请求地址替换成本地,截取当前名称进行+1作为下载名称,再获取请求头信息,以二进制流的形式进行转换,并通过ResponseEntity将文件内容以字节数组的形式作为响应主体返回给客户端

1.在controller层加入以下代码 

@RequestMapping(value="/download")public ResponseEntity<byte[]> download(HBook hBook, HttpServletRequest req){try {//先根据文件id查询对应图片信息HBook clz = this.hBookbiz.selectByPrimaryKey(hBook.getBid());String diskPath = PropertiesUtil.getValue("dir");String reqPath = PropertiesUtil.getValue("server");String realPath = clz.getImg().replace(reqPath,diskPath);String fileName = realPath.substring(realPath.lastIndexOf("/")+1);//下载关键代码File file=new File(realPath);HttpHeaders headers = new HttpHeaders();//http头信息String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码headers.setContentDispositionFormData("attachment", downloadFileName);headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);}catch (Exception e){e.printStackTrace();}return null;}

2.测试结果

三.多文件上传

多文件上传和普通文件上传的区别在于form表单提交的参数不同和controller层的上传形式不同

 1.controller层

获取上传文件的原始文件名:String filename = cfile.getOriginalFilename();

根据配置文件中指定的服务器目录保存上传文件:FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename)); 这里使用了 FileUtils 工具类将文件内容复制到指定的服务器目录中。

将文件名追加到 sb 对象中:sb.append(filename).append(",");

最后,将 sb.toString() 输出到控制台。

如果有任何异常发生,将打印异常栈轨迹。

最后,方法返回 "redirect:list",将客户端重定向到名为 list 的页面。

@RequestMapping("/uploads")public String uploads(HttpServletRequest req, HBook hBook, MultipartFile[] files){try {StringBuffer sb = new StringBuffer();for (MultipartFile cfile : files) {//思路://1) 将上传图片保存到服务器中的指定位置String dir = PropertiesUtil.getValue("dir");String server = PropertiesUtil.getValue("server");String filename = cfile.getOriginalFilename();FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));sb.append(filename).append(",");}System.out.println(sb.toString());} catch (Exception e) {e.printStackTrace();}return "redirect:list";}

2.前端页面

<form method="post" action="${pageContext.request.contextPath }/book/uploads" enctype="multipart/form-data">    <input type="file" name="files" multiple>    <button type="submit">上传</button></form>

3.测试结果

 

本期文件下载到这里就结束了,感谢各位大大的观看,三连是博主更新的动力,感谢谢谢谢谢!!!!

http://www.lryc.cn/news/160617.html

相关文章:

  • Leetcode143. 重排链表
  • Git 回顾小结
  • 响应式布局(3种) + flex计算
  • Pytorch从零开始实战01
  • inappropriate address 127.0.0.1 for the fudge command, line ignored 时间同步的时候报错
  • linux并发服务器 —— 项目实战(九)
  • 生信教程|替代模型选择
  • redis持久化、主从和哨兵架构
  • Python 连接 Oracle 详解
  • 认识模块化
  • 2023年及以后语言、视觉和生成模型的发展和展望
  • OpenLdap +PhpLdapAdmin + Grafana docker-compose部署安装
  • Java | 排序内容大总结
  • Go 语言入门指南:基础语法和常用特性解析
  • 20.添加HTTP模块
  • Qemu 架构 硬件模拟器
  • 通过starrocks jdbc外表查询sqlserver
  • ArcGIS 10.5安装教程!
  • ConstraintLayout约束布局
  • 通过pyinstaller将python项目打包成exe执行文件
  • P1068 [NOIP2009 普及组] 分数线划定
  • 应用在汽车新风系统中消毒杀菌的UVC灯珠
  • TOOLLLM: FACILITATING LARGE LANGUAGE MODELS TO MASTER 16000+ REAL-WORLD APIS
  • 【JavaSpring】spring接口-beanfactory和applicationcontext与事件解耦
  • 《深入理解Java虚拟机》——Java内存区域与内存溢出异常
  • 公众号hanniman往期精选
  • 谷粒商城----缓存与分布式锁
  • 【JavaEE进阶】Spring事务和事务传播机制
  • 【Hive】drop table需注意外部表
  • 【2023数学建模国赛】A题定日镜场的优化设计模型建立