SpringMVC框架(四)文件的上传下载,上下文路径
2024-08-24 08:17:46
文件目录:
SpringMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置扫描器 --> <context:component-scan base-package="com.maya.comtroller" /> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- <property name="prefix" value="/WEB-INF/"></property> --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 对于上传文件的解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件的最大值, 单位是b --> <property name="maxUploadSize" value="10240000"></property> <!-- 上传的单个文件的大小限制 --> <property name="maxUploadSizePerFile" value="1024000"></property> <!-- 转换字符集 --> <property name="defaultEncoding" value="utf-8"></property> </bean> <!-- 开启SpringMVC注解驱动 --> <mvc:annotation-driven> <!-- 改成false, 原因是在spring中默认使用的json格式的转换器是Jackson.jar中的转换器, 但实际开发中更受欢迎的是fastjson.jar --> <mvc:message-converters register-defaults="false"> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" /> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" /> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean id="fastJsonHttpMessagerConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <!-- 设置支持的媒体类型 --> <property name="supportedMediaTypes"> <list> <value>text/html; charset=utf-8</value> <value>application/json; charset=utf-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans>
controller层:
package com.maya.comtroller; import java.io.File; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; 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.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("file") //上传文件 public class TestFileController { @RequestMapping("/testUpload") public String testUpload( HttpServletRequest request, @RequestParam("myfile") MultipartFile file, String desp) throws IllegalStateException, IOException { String path = request.getServletContext().getRealPath("/MyFiles/"); Date date = new Date(); String orgFileName = date.getTime()+ ""; String typeName = file.getOriginalFilename(); String orgTypeName = typeName.substring(typeName.lastIndexOf(".")); System.out.println(path); // 上传文件的源文件名 File orgFile = new File(path + "/" + orgFileName + orgTypeName); file.transferTo(orgFile); return "success"; } //下载文件 @RequestMapping("/downloadFile") public ResponseEntity<byte[]> testDownLoad( HttpServletRequest request, String filename) throws Exception { String orgFilename = new String(filename.getBytes("iso-8859-1"), "utf-8"); String path = request.getServletContext().getRealPath("/myfiles/"); File orgFile = new File(path + "/" + orgFilename); // 设置请求头信息 HttpHeaders hh = new HttpHeaders(); // 告诉前台, 以(attachement, 就是下载)的方式打开文件 hh.setContentDispositionFormData("attachment", new String(orgFilename.getBytes("utf-8"), "iso-8859-1")); // 以二进制流的形式传输文件, 这是最常见的下载方式 hh.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(orgFile), hh, HttpStatus.CREATED); } }
jsp页面:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.io.File"%> <!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"> <title>Insert title here</title> </head> <body> <div style="margin:100px"> <form action="file/testUpload.do" method="post" enctype="multipart/form-data"> <input name="desp" /> <input type="file" multiple="multiple" name="myfile" /><br> <input type="submit" value="Submit" /> </form> <hr> <% String path = request.getServletContext().getRealPath("/MyFiles/"); File f = new File(path); File[] files=f.listFiles(); //获取路径下的文件名 for(File fi:files){ out.print("<a href='file/downloadFile.do?filename="+fi.getName()+"'>"+fi.getName()+"</a><br>"); } %> </div> </body> </html>
这种方式只能进行单文件的上传,不建议使用该方式进行多文件上传,应考虑其他方式。如果要使用该方式进行多文件上传,可以,使用如下代码:
from表单中增加一个
multiple="multiple"
<form action="<%=basePath %>/file/testUpload.do" method="post" enctype="multipart/form-data"> <input name="myfile" multiple="multiple" type="file" /><input type="submit" value="Submit" /> </form>
后台:
@Controller @RequestMapping("file") public class TestFileController { @RequestMapping("/testUpload") public String testUpload( HttpServletRequest request, @RequestParam("myfile") MultipartFile[] files, String desp) throws IllegalStateException, IOException { String path = request.getServletContext().getRealPath("/files/"); for(MultipartFile file : files) { Date date = new Date(); String orgFileName = date.getTime()+ ""; String typeName = file.getOriginalFilename(); String orgTypeName = typeName.substring(typeName.lastIndexOf(".")); File orgFile = new File(path + "/" + orgFileName + orgTypeName); file.transferTo(orgFile); } }
但是,如果在上传成功之后的提示页面通过超链接返回文件上传页面,会报404错
因为有注解
@RequestMapping("file")
定义了请求的前缀是指向 file 下的,所以执行方法最后返回的时候,会从 file 下去寻找视图层的页面,所以无法找到
解决方法:
可以通过上下文路径:
<% String basePath = request.getContextPath(); // 上下文路径 %>
<%=basePath %>
获取当前项目名,并写在请求的路径中
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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"> <title>Insert title here</title> <% String basePath = request.getContextPath(); // 上下文路径 %> </head> <body> 上传成功 ! <a href="<%=basePath %>/filetest.jsp">返回文件页面</a> </body> </html>
最新文章
- BOM DOM Event事件笔记....
- NPTL vs PThread
- Python基础第三篇
- Java for LeetCode 168 Excel Sheet Column Title
- Qemu文档
- C++ 拆分字符串-copy()
- 在Delphi中实现动画窗口
- hdu 1044 Collect More Jewels(bfs+状态压缩)
- .NET多线程执行函数
- CodeSmith和PowerDesigner的使用安装和数据库创建
- delphi tidhttp 超时的解决方案
- N - Picture - poj 1177(扫描线求周长)
- HDU 5831 Rikka with Parenthesis II
- Spring MVC的handlermapping之RequestMappingHandlerMapping初始化
- BZOJ_2962_序列操作_线段树
- PO、POJO、BO、DTO、VO之间的区别(转)
- Visual C++ 6.0中if..else..的简单用法和基本格式
- android高级页面效果集锦
- String,StringBuilder和StringBuffer区别
- cookie、localStorage、sessionStorage 的生命周期