SpringMVC框架(四)文件的上传下载,上下文路径
文件目录:

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>
SpringMVC框架(四)文件的上传下载,上下文路径的更多相关文章
- SSM框架之中如何进行文件的上传下载
SSM框架的整合请看我之前的博客:http://www.cnblogs.com/1314wamm/p/6834266.html 现在我们先看如何编写文件的上传下载:你先看你的pom.xml中是否有文件 ...
- SpringMVC+Ajax实现文件批量上传和下载功能实例代码
需求: 文件批量上传,支持断点续传. 文件批量下载,支持断点续传. 使用JS能够实现批量下载,能够提供接口从指定url中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...
- SocketIo+SpringMvc实现文件的上传下载
SocketIo+SpringMvc实现文件的上传下载 socketIo不仅可以用来做聊天工具,也可以实现局域网(当然你如果有外网也可用外网)内实现文件的上传和下载,下面是代码的效果演示: GIT地址 ...
- Spring实现文件的上传下载
背景:之前一直做的是数据库的增删改查工作,对于文件的上传下载比较排斥,今天研究了下具体的实现,发现其实是很简单.此处不仅要实现单文件的上传,还要实现多文件的上传. 单文件的下载知道了,多文件的下载呢? ...
- 在Window的IIS中创建FTP的Site并用C#进行文件的上传下载
文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服务器计算机上. 然后,远程计算机可以使用 FTP ...
- 创建FTP的Site并用C#进行文件的上传下载
创建FTP的Site并用C#进行文件的上传下载 文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服 ...
- linux链接及文件互相上传下载
若排版紊乱可查看我的个人博客原文地址 基本操作 本篇博客主要介绍如何去链接远程的linux主机及如何实现本地与远程主机之间文件的上传下载操作,下面的linux系统是CentOS6.6 链接远程linu ...
- JAVAWEB之文件的上传下载
文件上传下载 文件上传: 本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将 ...
- python使用ftplib模块实现FTP文件的上传下载
python已经默认安装了ftplib模块,用其中的FTP类可以实现FTP文件的上传下载 FTP文件上传下载 # coding:utf8 from ftplib import FTP def uplo ...
- php文件夹上传下载控件分享
用过浏览器的开发人员都对大文件上传与下载比较困扰,之前遇到了一个php文件夹上传下载的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下是实例的部分脚本文件 这里我先 ...
随机推荐
- Java泛型:泛型类,泛型接口和泛型方法
转自: https://segmentfault.com/a/1190000002646193 泛型的产生很多缘由是因为 容器类 的创建 泛型类 容器类应该算得上最具重用性的类库之一.先来看一个没有 ...
- input长度随输入内容动态变化 input光标定位在最右侧
<input type="text" onkeydown="this.onkeyup();" onkeyup="this.size=(this. ...
- 协处理器CP15介绍—MCR/MRC指令(6)
概述:在基于ARM的嵌入式应用系统中,存储系统的操作通常是由协处理器CP15完成的.CP15包含16个32位的寄存器,其编号为0-15. 而访问CP15寄存器的指令主要是MCR和MRC这两个指令. 例 ...
- [Unity 设计模式]桥接模式(BridgePattern)
1.前言 继上一讲IOC模式的基础上继续本讲桥接模式,笔者感觉桥接模式是23种设计模式中桥接模式是最好用但也是最难理解的设计模式之一,23中设计模式就好武侠剧中一本武功秘籍,我们在工作过程中想要熟练运 ...
- 编程零基础应当如何开始学习 Python?
提前说一下,这篇福利多多,别的不说,直接让你玩回最有手感的怀旧游戏,参数贴图很方便自己可以根据喜好修改哦. 本篇通过以下四块展开,提供大量资源对应. 选一个好版本 有没有看过<在下坂本,有何贵干 ...
- Scrapy 爬虫入门 +实战
爬虫,其实很早就有涉及到这个点,但是一直没有深入,今天来搞爬虫.选择了,scrapy这个框架 http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/tut ...
- 团队作业4——第一次项目冲刺(Alpha版本)2017.4.27
2017.04.27 天气阴沉 小雨. 时间:上午 9:35 ---10:10分 地点:陆大314实验室 会议内容:每天充分利用好大课间的时间,今天对昨天的的细节问题进行了讨论及方法更正.时间不等人这 ...
- java 课程设计 购物车系统 个人
Q1.团队课程设计博客链接 团队博客 Q2.个人负责模块或任务说明 我主要负责main函数的编写和系统中瞎看功能代码的编写. Q3.自己的代码提交记录截图 main函数代码如下: public sta ...
- 201521123053《Java课程设计》第十四周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 知识点: 创建表的命令有若干行,如果中间某行输入错误,不能修改:可以使用记事本现将命令输入,然后复制粘贴到mys ...
- [06] Session实现机制以及和Cookie的区别
1.为什么有Session和Cookie 根据早期的HTTP协议,每次request-reponse时,都要重新建立TCP连接.TCP连接每次都重新建立,所以服务器无法知道上次请求和本次请求是否来自于 ...