南宁网站建设推广服务,上海青浦区网站建设公司,小学生做网站软件,网站建设流程机构SpringMVC是一个基于Java的Web框架#xff0c;它提供了一套用于构建Web应用程序的开发模型。在SpringMVC中#xff0c;文件上传和下载是常见的功能之一。
SpringMVC文件上传和下载的介绍#xff1a;
介绍文件上传#xff1a; 在SpringMVC中#xff0c;文件上传功能可以通…SpringMVC是一个基于Java的Web框架它提供了一套用于构建Web应用程序的开发模型。在SpringMVC中文件上传和下载是常见的功能之一。
SpringMVC文件上传和下载的介绍
介绍文件上传 在SpringMVC中文件上传功能可以通过使用CommonsMultipartResolver解析器来实现。这个解析器需要在Spring配置文件中进行配置。在表单中添加一个input typefile标签并设置对应的表单属性和控制器方法参数。在控制器方法中使用MultipartFile对象来接收上传的文件。可以通过该对象获取文件名、大小、内容等信息。处理上传的文件可以将文件保存到本地磁盘或者存储到数据库中具体操作根据业务需求来决定。 介绍文件下载 在SpringMVC中文件下载可以通过在控制器方法中设置响应头和输出流来实现。在控制器方法中设置响应头Content-Disposition为attachment; filenamexxx其中filename指定要下载的文件名。使用OutputStream将文件内容写入响应流实现文件下载。可以根据需要对下载文件进行权限验证、文件类型限制等处理。 需要注意的是文件上传和下载可能涉及到安全性考虑比如文件大小限制、文件类型检查、防止文件覆盖等开发者需要根据实际情况添加相应的处理逻辑。
希望这个简要介绍能对你有所帮助如果还有其他问题请继续提问。
文件上传
依赖 dependencygroupIdcommons-fileupload/groupIdartifactIdcommons-fileupload/artifactIdversion1.3.3/version
/dependency
文件上传解析器
根据上章进行改变在我们的spring-mvc.xml中增加以下配置
!-- 处理文件上传下载问题--bean idmultipartResolver classorg.springframework.web.multipart.commons.CommonsMultipartResolver!-- 必须和用户JSP 的pageEncoding属性一致以便正确解析表单的内容 --property namedefaultEncoding valueUTF-8/property!-- 文件最大大小(字节) 1024*1024*5050M--property namemaxUploadSize value52428800/property!--resolveLazily属性启用是为了推迟文件解析以便捕获文件大小异常--property nameresolveLazily valuetrue//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
dirD:/temp/upload/
server/upload/
sql
select idlistPager resultTypecom.zhanghao.model.Music parameterTypecom.zhanghao.model.Music select*from jay_musicwhereif testmname ! nulland mname like concat(%,#{mname},%)/if/where/select
在他自动生成中的时候在mapper类中增加
ListMusic 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 hreforder/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 languagejava contentTypetext/html; charsetUTF-8pageEncodingUTF-8%
% taglib urihttp://jsp.veryedu.cn prefixz%
% taglib urihttp://java.sun.com/jsp/jstl/core prefixc%
!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd
html
headmeta http-equivContent-Type contenttext/html; charsetUTF-8linkhrefhttps://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.cssrelstylesheetscriptsrchttps://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js/scripttitleJayChouxs 学生列表/titlestyle typetext/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 classform-inlineaction${pageContext.request.contextPath }/mic/list methodpostdiv classform-group mb-2input typetext classform-control-plaintext namemnameplaceholder请输入学生名称!-- input namerows value20 typehidden --!-- 不想分页 --
%-- input namepagination valuefalse typehidden--%/divbutton typesubmit classbtn btn-primary mb-2查询/buttona classbtn btn-primary mb-2 href${pageContext.request.contextPath }/mic/preSave新增/a
/formtable classtable table-stripedtheadtrth scopecol学生编号/thth scopecol学生名称/thth scopecol学生辑/thth scopecol学生贡词/thth scopecol学生图片/th/tr/theadtbodyc:forEach varb items${lst }trtd${b.mid }/tdtd${b.mname }/tdtd${b.mtype }/tdtd${b.minfo }/tdtdimg src${b.mpic } styleheight: 60px;width: 60px/tdtda href${pageContext.request.contextPath }/mic/preSave?mid${b.mid}修改/aa href${pageContext.request.contextPath }/mic/del/${b.mid}删除/aa href${pageContext.request.contextPath }/page/mic/upload?mid${b.mid}图片上传/aa 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(dirfileName));music.setMpic(serverfileName);musicBiz.updateByPrimaryKeySelective(music);} catch (IOException e) {e.printStackTrace();}return redirect:list;}
图片上传的操作页面
% page contentTypetext/html;charsetUTF-8 languagejava %
html
headtitle专辑图片上传/title
/head
body
form action${pageContext.request.contextPath}/mic/upload methodpost enctypemultipart/form-datalabel歌曲编号/labelinput typetext namemid readonlyreadonly value${param.mid}/br/label专辑图片/labelinput typefile namem/br/input typesubmit value上传图片/
/form
form methodpost action${pageContext.request.contextPath}/mic/uploads enctypemultipart/form-datainput typefile namefiles multiplebutton typesubmit上传/button
/form
/body
/html
文件下载 //文件下载实现RequestMapping(value/download)public ResponseEntitybyte[] 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 filenew 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 ResponseEntitybyte[](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(dirfilename));sb.append(filename).append(,);}System.out.println(sb.toString());} catch (Exception e) {e.printStackTrace();}return redirect:list;}