SpringMVC是一个基于Java的Web框架,它提供了一套用于构建Web应用程序的开发模型。在SpringMVC中,文件上传和下载是常见的功能之一。
SpringMVC文件上传和下载的介绍:
介绍文件上传:
- 在SpringMVC中,文件上传功能可以通过使用
CommonsMultipartResolver
解析器来实现。这个解析器需要在Spring配置文件中进行配置。- 在表单中添加一个
<input type="file">
标签,并设置对应的表单属性和控制器方法参数。- 在控制器方法中,使用
MultipartFile
对象来接收上传的文件。可以通过该对象获取文件名、大小、内容等信息。- 处理上传的文件,可以将文件保存到本地磁盘或者存储到数据库中,具体操作根据业务需求来决定。
介绍文件下载:
- 在SpringMVC中,文件下载可以通过在控制器方法中设置响应头和输出流来实现。
- 在控制器方法中,设置响应头
Content-Disposition
为attachment; filename=xxx
,其中filename
指定要下载的文件名。- 使用
OutputStream
将文件内容写入响应流,实现文件下载。- 可以根据需要对下载文件进行权限验证、文件类型限制等处理。
需要注意的是,文件上传和下载可能涉及到安全性考虑,比如文件大小限制、文件类型检查、防止文件覆盖等,开发者需要根据实际情况添加相应的处理逻辑。
希望这个简要介绍能对你有所帮助!如果还有其他问题,请继续提问。
文件上传
依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
文件上传解析器
根据上章进行改变在我们的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>
完成后配置服务器存放文件地址,服务器我们可以创造一个包代替
PropertiesUtil
package 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);
}
}
resource.properties
创造resource.properties
dir=D:/temp/upload/
server=/upload/
sql
<select id="listPager" resultType="com.zhanghao.model.Music" parameterType="com.zhanghao.model.Music" >
select
*
from jay_music
<where>
<if test="mname != null">
and mname like concat('%',#{mname},'%')
</if>
</where>
</select>
在他自动生成中的时候在mapper类中增加:
List<Music> listPager(Music music);
PageController
package com.zhanghao.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author zhanghao
* @site
* @company s集团
* @create 2023-09-08-15:01
*
* 用来处理页面跳转
*/
@Controller
public class PageController {
//<a href="order/preSave">新增</a> 新增界面
@RequestMapping("/page/{page}")
public String toPage(@PathVariable("page") String page){
return page;
}
@RequestMapping("/page/{dir}/{page}")
public String toDirPage(@PathVariable("dir") String dir,
@PathVariable("page") String page){
return dir + "/" + page;
}
}
主页
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
rel="stylesheet">
<script
src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>JayChouxs 学生列表</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/mic/list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="mname"
placeholder="请输入学生名称">
<!-- <input name="rows" value="20" type="hidden"> -->
<!-- 不想分页 -->
<%-- <input name="pagination" value="false" type="hidden">--%>
</div>
<button type="submit" class="btn btn-primary mb-2">查询</button>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/mic/preSave">新增</a>
</form>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">学生编号</th>
<th scope="col">学生名称</th>
<th scope="col">学生辑</th>
<th scope="col">学生贡词</th>
<th scope="col">学生图片</th>
</tr>
</thead>
<tbody>
<c:forEach var="b" items="${lst }">
<tr>
<td>${b.mid }</td>
<td>${b.mname }</td>
<td>${b.mtype }</td>
<td>${b.minfo }</td>
<td>
<img src="${b.mpic }" style="height: 60px;width: 60px">
</td>
<td>
<a href="${pageContext.request.contextPath }/mic/preSave?mid=${b.mid}">修改</a>
<a href="${pageContext.request.contextPath }/mic/del/${b.mid}">删除</a>
<a href="${pageContext.request.contextPath }/page/mic/upload?mid=${b.mid}">图片上传</a>
<a href="${pageContext.request.contextPath }/mic/download?mid=${b.mid}">图片下载</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>
${pageBean }
</body>
</html>
文件上传
文件上传指将本地计算机中的文件通过网络传输到服务器的过程。在Web开发中,文件上传是一个常见的功能,常用于用户提交文件、图片、视频等数据,例如在论坛上上传头像、在电商网站上上传商品图片等。常见的文件上传方式有两种:表单提交(form表单上传)和Ajax异步上传。
表单提交方式是一种传统的文件上传方式。用户通过一个form表单提交相关信息和文件,服务器端收到表单提交后,通过解析表单进行文件上传。该方式的优点是支持大文件上传和浏览器兼容性好,缺点是页面需要刷新提交表单,用户体验有些糟糕。
Ajax异步上传方式是通过JavaScript将文件传输到服务器端,该方式通过XMLHttpRequest对象实现。Ajax异步上传采用无刷新方式,可以实现较好的用户体验,并且可以方便地显示上传进度和上传结果等信息。缺点是需要同时支持HTML5的FormData对象和Ajax异步上传技术。
在实现文件上传时,需要注意安全性问题,例如文件上传限制、防止文件包含恶意代码等。服务器端需要对上传的文件进行验证和安全过滤,确保上传的文件不会被用作恶意活动。
MusicController控制器中增加文件上传的方法
//文件上传
@RequestMapping("/upload")
public String upload(Music music,MultipartFile m){
try {
// 3.后端可以直接利用mutipartFile类,接受前端传递到后台的文件
//上传的图片真实存放地址
String dir = PropertiesUtil.getValue("dir");
//网络访问地址
String server = PropertiesUtil.getValue("server");
String fileName = m.getOriginalFilename();
System.out.println("文件名:"+fileName);
System.out.println("文件类别:"+m.getContentType());
//4.将文件转成流,然后写入服务器(某一个硬盘)
FileUtils.copyInputStreamToFile(m.getInputStream(),new File(dir+fileName));
music.setMpic(server+fileName);
musicBiz.updateByPrimaryKeySelective(music);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:list";
}
图片上传的操作页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>专辑图片上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/mic/upload" method="post" enctype="multipart/form-data">
<label>歌曲编号:</label><input type="text" name="mid" readonly="readonly" value="${param.mid}"/><br/>
<label>专辑图片:</label><input type="file" name="m"/><br/>
<input type="submit" value="上传图片"/>
</form>
<form method="post" action="${pageContext.request.contextPath}/mic/uploads" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<button type="submit">上传</button>
</form>
</body>
</html>
文件下载
//文件下载实现
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(Music music,HttpServletRequest req){
try {
//先根据文件id查询对应图片信息
Music mic = this.musicBiz.selectByPrimaryKey(music.getMid());
String diskPath = PropertiesUtil.getValue("dir");
String reqPath = PropertiesUtil.getValue("server");
String realPath = mic.getMpic().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;
jrebel&多文件上传
多文件上传和普通文件上传是指向Web服务器上传文件时的两种不同方式。
普通文件上传只支持单个文件上传。用户选择要上传的文件后,需要等待文件上传完毕才能上传下一个文件。这种方法适合上传单个文件,但当需要上传多个文件时,不仅会很麻烦,也会耗费较多的时间。
而多文件上传可以同时上传多个文件。用户可以在一个窗口中选择多个文件,然后一起上传。在上传多个文件时,用户可以看到已上传和待上传文件的进度。这种方法适合批量上传文件,可以节省用户的时间和精力。
在实现多文件上传功能时,常见的方法是使用JavaScript和AJAX技术,通过JavaScript获取用户选择的文件,然后使用AJAX将文件发送到服务器端。一些流行的JavaScript库,如jQuery和Bootstrap,也提供了方便的多文件上传插件。
//多文件上传
@RequestMapping("/uploads")
public String uploads(HttpServletRequest req, Music music, 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";
}