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文件夹上传下载的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下是实例的部分脚本文件 这里我先 ...
随机推荐
- C#多线程的用法7-线程间的协作ManualResetEvent
ManualResetEvent:手动重置事件,它用于线程间同步时用法非常简单也易于理解. private static void MultiThreadSynergicWithManualReset ...
- 线上Java程序导致服务器CPU占用率过高的问题排除过程
博文转至:http://www.jianshu.com/p/3667157d63bb,博文更好效果看原版,转本博文的目的就算是个书签吧,需要时候可以定位原文学习 1.故障现象 客服同事反馈平台系统运行 ...
- poj2942(双联通分量,交叉染色判二分图)
题意:一些骑士,他们有些人之间有矛盾,现在要求选出一些骑士围成一圈,圈要满足如下条件:1.人数大于1.2.总人数为奇数.3.有仇恨的骑士不能挨着坐.问有几个骑士不能和任何人形成任何的圆圈. 思路:首先 ...
- java1.8新特性
转自:http://www.oschina.NET/translate/everything-about-Java-8 建议去看原文,此处转载只是为了记录. 这篇文章是对Java8中即将到来的改进做一 ...
- spring的配置文件和加载
①:创建applicationContext.xml配置文件放在src下 //applicationContext.xml代码 <?xml version="1.0" enc ...
- 201521123099 《Java程序设计》第6周学习总结
1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. 注1:关键词与内容不求多,但概念之间的联系要清晰,内容覆盖 ...
- 201521123008<java程序设计>第三周实验总结
1.本周学习总结 2.书面作业 1.代码阅读 public class Test1 { private int i = 1;//这行不能修改 private static int j = 2; pub ...
- 201521123077 《Java程序设计》第1周学习总结
1. 本章学习总结 java语言的历史 dos下运行 java文件 Math ,String ,Scanner,Interger等常用类的使用 jdk,jre,jvm等概念的了解 classpath, ...
- Cookie和Session总结
Cookie概述 Cookie是什么? Cookie是一小段文本信息,伴随着用户请求和页面在Web服务器和浏览器之间传递.Cookie包含每次用户访问站点时Web应用程序都可以读取 ...
- Markdown编辑后
一个例子: 例子开始 1. 本章学习总结 今天主要学习了三个知识点 封装 继承 多态 2. 书面作业 Q1. java HelloWorld命令中,HelloWorld这个参数是什么含义? 今天学了一 ...