汽车案例网站,淮安住房与城乡建设部网站,内蒙建设厅网站怎么查建筑电工证,聊天网站开发SpringMVC之文件上传下载 一、文件上传二、文件下载三、多文件上传 一、文件上传
配置多功能视图解析器#xff08;spring-mvc.xml#xff09;#xff1a;在Spring MVC的配置文件#xff08;spring-mvc.xml#xff09;中配置多功能视图解析器#xff0c;以支持文件上传。… SpringMVC之文件上传下载 一、文件上传二、文件下载三、多文件上传 一、文件上传
配置多功能视图解析器spring-mvc.xml在Spring MVC的配置文件spring-mvc.xml中配置多功能视图解析器以支持文件上传。
添加文件上传页面upload.jsp创建一个名为upload.jsp的JSP页面用于用户上传文件。
做硬盘网络路径映射配置服务器的硬盘路径映射到网络路径确保上传的文件可以被访问和处理。
编写一个处理页面跳转的类创建一个处理页面跳转的Java类比如PageController.java或ClazzController.java用于处理上传文件后的页面跳转逻辑。
package com.niyin.web;import com.niyin.biz.tyBiz;
import com.niyin.model.ty;
import com.niyin.utils.PageBean;
import com.niyin.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;Controller
RequestMapping(/clz)
public class tyController {Autowiredprivate tyBiz tyBiz;RequestMapping(/list)public String list(ty t, HttpServletRequest request){PageBean pageBeanagenew PageBean();pageBeanage.setRequest(request);Listty books tyBiz.selectByPager(t, pageBeanage);request.setAttribute(lst,books);request.setAttribute(pageBean,pageBeanage);return list;};RequestMapping(/add)public String add(ty t){int i tyBiz.insertSelective(t);return redirect:list;};RequestMapping(/del)public String del(ty t){tyBiz.deleteByPrimaryKey(t.getTid());return redirect:list;};RequestMapping(/edit)public String edit(ty t){tyBiz.updateByPrimaryKeySelective(t);return redirect:list;};RequestMapping(/preSave)public String preSave(ty t, Model model) {if (t!nullt.getTid()!nullt.getTid()!0){ty ts tyBiz.selectByPrimaryKey(t.getTid());model.addAttribute(ts,ts);}return edit;}RequestMapping(/upload)
public String upload(ty t,MultipartFile cfile){try {String dir PropertiesUtil.getValue(dir);String serverPropertiesUtil.getValue(server);String Filename cfile.getOriginalFilename();System.out.println(文件名Filename);System.out.println(文件类别cfile.getContentType());t.setTimage(serverFilename);tyBiz.updateByPrimaryKeySelective(t);FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dirFilename));} catch (IOException e) {e.printStackTrace();}return redirect:list;
}RequestMapping(value/download)public ResponseEntitybyte[] download(ty t,HttpServletRequest req){try {//先根据文件id查询对应图片信息 ty ts this.tyBiz.selectByPrimaryKey(t.getTid());String diskPath PropertiesUtil.getValue(dir);String reqPath PropertiesUtil.getValue(server);String realPath ts.getTimage().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;}RequestMapping(/uploads)public String uploads(HttpServletRequest req, ty t, 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;}}package com.niyin.web;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;Controller
public class PageController {
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;}RequestMapping(/order/presave)public String orderpre() {return /order/presave;}RequestMapping(/clz/presave)public String clzerpre() {return /clz/presave;}}初步模拟上传文件实现一个初步的文件上传功能可以将上传的文件保存到服务器指定的目录。
配置目录的配置文件创建一个配置文件比如resource.properties用于配置上传文件保存的目录。 dirD:/temp/upload/ server/upload/ 最终实现文件上传并显示完成文件上传功能的开发同时可以在页面上显示上传的文件列表或其他相关信息。
二、文件下载
方法代码编写一个方法代码用于处理文件下载请求。该方法根据请求参数或文件路径读取相应的文件并将文件内容写入HTTP响应流中实现文件下载。
package com.niyin.web;import com.niyin.biz.tyBiz;
import com.niyin.model.ty;
import com.niyin.utils.PageBean;
import com.niyin.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;Controller
RequestMapping(/clz)
public class tyController {Autowiredprivate tyBiz tyBiz;RequestMapping(/list)public String list(ty t, HttpServletRequest request){PageBean pageBeanagenew PageBean();pageBeanage.setRequest(request);Listty books tyBiz.selectByPager(t, pageBeanage);request.setAttribute(lst,books);request.setAttribute(pageBean,pageBeanage);return list;};RequestMapping(/add)public String add(ty t){int i tyBiz.insertSelective(t);return redirect:list;};RequestMapping(/del)public String del(ty t){tyBiz.deleteByPrimaryKey(t.getTid());return redirect:list;};RequestMapping(/edit)public String edit(ty t){tyBiz.updateByPrimaryKeySelective(t);return redirect:list;};RequestMapping(/preSave)public String preSave(ty t, Model model) {if (t!nullt.getTid()!nullt.getTid()!0){ty ts tyBiz.selectByPrimaryKey(t.getTid());model.addAttribute(ts,ts);}return edit;}RequestMapping(/upload)
public String upload(ty t,MultipartFile cfile){try {String dir PropertiesUtil.getValue(dir);String serverPropertiesUtil.getValue(server);String Filename cfile.getOriginalFilename();System.out.println(文件名Filename);System.out.println(文件类别cfile.getContentType());t.setTimage(serverFilename);tyBiz.updateByPrimaryKeySelective(t);FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dirFilename));} catch (IOException e) {e.printStackTrace();}return redirect:list;
}RequestMapping(value/download)public ResponseEntitybyte[] download(ty t,HttpServletRequest req){try {//先根据文件id查询对应图片信息 ty ts this.tyBiz.selectByPrimaryKey(t.getTid());String diskPath PropertiesUtil.getValue(dir);String reqPath PropertiesUtil.getValue(server);String realPath ts.getTimage().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;}RequestMapping(/uploads)public String uploads(HttpServletRequest req, ty t, 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;}}
JSP页面代码创建一个JSP页面用于触发文件下载请求。在该页面中可以使用超链接或按钮等方式触发文件下载的方法。
%--Created by IntelliJ IDEA.User: 林墨Date: 2023/9/9Time: 14:20To change this template use File | Settings | File Templates.
--%
% page contentTypetext/html;charsetUTF-8 languagejava %
html
headtitle头像上传/title
/head
body
form action${ctx}/clz/upload methodpost enctypemultipart/form-datalabel班级编号/labelinput typetext nametid readonlyreadonly value${param.tid}/br/label班级图片/labelinput typefile namecfile/br/input typesubmit value上传图片/
/formform methodpost action${ctx}/clz/uploads enctypemultipart/form-datainput typefile namefiles multiplebutton typesubmit上传/button/form
/body
/html效果测试运行应用程序访问下载页面并点击下载链接或按钮验证文件下载功能是否正常工作。
三、多文件上传
jsp页面显示代码修改上传页面upload.jsp支持同时上传多个文件。可以使用HTML的input标签设置multiple属性以允许选择多个文件。
% page languagejava contentTypetext/html; charsetUTF-8pageEncodingUTF-8%
!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-8title博客的编辑界面/title
/head
body
form action${pageContext.request.contextPath }/clz/${empty ts ? add : edit} methodpostid:input typetext nametid value${ts.tid }brbname:input typetext nametname value${ts.tname }brprice:input typetext nametprice value${ts.tprice }brprice:input typetext nametiamge value${ts.timage}brinput typesubmit
/form
/body
/html多文件上传方法修改文件上传处理逻辑使其能够处理同时上传的多个文件。可以使用循环遍历的方式依次处理每个上传的文件。
package com.niyin.web;import com.niyin.biz.tyBiz;
import com.niyin.model.ty;
import com.niyin.utils.PageBean;
import com.niyin.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;Controller
RequestMapping(/clz)
public class tyController {Autowiredprivate tyBiz tyBiz;RequestMapping(/list)public String list(ty t, HttpServletRequest request){PageBean pageBeanagenew PageBean();pageBeanage.setRequest(request);Listty books tyBiz.selectByPager(t, pageBeanage);request.setAttribute(lst,books);request.setAttribute(pageBean,pageBeanage);return list;};RequestMapping(/add)public String add(ty t){int i tyBiz.insertSelective(t);return redirect:list;};RequestMapping(/del)public String del(ty t){tyBiz.deleteByPrimaryKey(t.getTid());return redirect:list;};RequestMapping(/edit)public String edit(ty t){tyBiz.updateByPrimaryKeySelective(t);return redirect:list;};RequestMapping(/preSave)public String preSave(ty t, Model model) {if (t!nullt.getTid()!nullt.getTid()!0){ty ts tyBiz.selectByPrimaryKey(t.getTid());model.addAttribute(ts,ts);}return edit;}RequestMapping(/upload)
public String upload(ty t,MultipartFile cfile){try {String dir PropertiesUtil.getValue(dir);String serverPropertiesUtil.getValue(server);String Filename cfile.getOriginalFilename();System.out.println(文件名Filename);System.out.println(文件类别cfile.getContentType());t.setTimage(serverFilename);tyBiz.updateByPrimaryKeySelective(t);FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dirFilename));} catch (IOException e) {e.printStackTrace();}return redirect:list;
}RequestMapping(value/download)public ResponseEntitybyte[] download(ty t,HttpServletRequest req){try {//先根据文件id查询对应图片信息 ty ts this.tyBiz.selectByPrimaryKey(t.getTid());String diskPath PropertiesUtil.getValue(dir);String reqPath PropertiesUtil.getValue(server);String realPath ts.getTimage().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;}RequestMapping(/uploads)public String uploads(HttpServletRequest req, ty t, 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;}}测试多文件上传通过在上传页面选择多个文件并点击上传按钮测试多文件上传功能是否正常工作。 可以看到已经成功了