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文件夹上传下载的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下是实例的部分脚本文件 这里我先 ...
随机推荐
- Selenium八种基本定位方式---基于python
from selenium import webdriver driver=webdriver.Firefox() driver.get("https://www.baidu.com&qu ...
- C#将Excel数据表导入SQL数据库的两种方法(转)
最近用写个winform程序想用excel 文件导入数据库中,网上寻求办法,找到了这个经过尝试可以使用. 方法一: 实现在c#中可高效的将excel数据导入到sqlserver数据库中,很多人通过循环 ...
- 规则集Set与线性表List性能分析
前言 本章节将通过实验,测试规则集与线性表的性能.那么如何进行实验呢?针对不同的集合都进行指定数量元素的添加和删除操作,计算耗费时间进行分析. 那么,前两个章节呢,我们分别讲述了什么时候使用Set以及 ...
- JavaSE(十)集合之List
前面一篇的corejava讲的是集合的概述,这一篇我将详细的和大家讲解一下Collection下面的List.set.queue这三个子接口.希望大家能得到提升. 一.List接口 1.1.List接 ...
- Java 多线程(一) 基础知识与概念
多线程Multi-Thread 基础 线程概念 线程就是程序中单独顺序的流控制. 线程本身不能运行,它只能用于程序中. 说明:线程是程序内的顺序控制流,只能使用分配给程序的资源和环境. 进程 进程:执 ...
- 【Beta】 第六次Daily Scrum Meeting
一.本次会议为第六次meeting会议 二.时间:10:00AM-10:20AM 地点:禹州楼 三.会议站立式照片 四.今日任务安排 成员 昨日任务 今日任务 林晓芳 对目前完成的模块进行全面测试,并 ...
- 四则运算题目生成程序(基于控制台)(Bug修改)
针对上个程序中出现的bug进行修改 https://git.coding.net/cx873230936/calculator.git Bug: 1.控制台输入问题数问题 a.不能处理用户输入负数. ...
- 个人作业2-英语学习案例app分析
第一部分 调研, 评测 (软件的bug,功能评测,黑箱测试, 第8章 用户调研, 12 章 软件的用户体验) 下载并使用,描述最简单直观的个人第一次上手体验. ①个人感觉还不错,词典的首页页面挺好看的 ...
- 201521123092《java程序设计》第六周学习总结
1.本周学习总结 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. 2.书面作业 1.clone方法 1.1 Object对象中的clo ...
- 201521123103 《Java学习笔记》 第四周学习总结
一.本周学习总结 1.1 尝试使用思维导图总结有关继承的知识点. 1.2 使用常规方法总结其他上课内容. (1)多态性:相同形态,不同行为(不同的定义): (2)多态绑定:运行时能够自动地选择调用哪个 ...