我们经常会使用的一个功能是文件下载,既然有文件下载就会有文件上传,下面我们来看一下文件上传是如何实现的

首先准备好一个页面

jsp

<style type="text/css">
form{
margin:0px auto;
border:1px solid red;
width:500px;
padding:20px;
}
</style>
</head> <body>
<form action="${pageContext.request.contextPath }/frist.do" method="post" enctype="multipart/form-data">
<h1>文件上传</h1>
文件:<input type="file" name="uploadFile"/><br/>
文件:<input type="file" name="uploadFile"/><br/>
文件:<input type="file" name="uploadFile"/><br/>
<input type="submit" value="上传">
</form>
</body>

单文件上传

通过对文件的大小来判断是否有文件

通过文件的类型来判断是否是允许

@Controller
public class MyController {
@RequestMapping(value="/frist.do", method=RequestMethod.POST)
public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{
if(uploadFile.getSize()>0){
//02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹 转换成绝对路径
String path = session.getServletContext().getRealPath("/upload");
//01.获取文件名作为保存到服务器的文件名称
String fileName=uploadFile.getOriginalFilename();
if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
//03.路径拼接
File file = new File(path,fileName);
uploadFile.transferTo(file);
}
return "welcome.jsp";
}
return "error.jsp";
}

applicationContext.xml配置

<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"> <!-- 配置包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan> <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!-- 客户端发送数据的编码 -->
<property name="maxUploadSize" value="5242880"></property><!-- 上传文件的大小 -->
<!-- <property name="uploadTempDir" value="/upload"></property> -->
</bean>
<!-- mvc注解驱动 -->
<mvc:annotation-driven /> </beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- ================spring mvc 适配器================ -->  
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
 <!-- ================================================== -->  <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

  

多文件上传(多文件上传与单文件上传配置相同下面介绍一下不同的地方)

标记为红色的字段为多文件上传 与单文件上传的区别

     @RequestMapping(value="/firstdown.do")
public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session)throws Exception{
for (MultipartFile item : uploadFile) { if(item.getSize()>0){
//02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹 转换成绝对路径
String path = session.getServletContext().getRealPath("/upload");
//01.获取文件名作为保存到服务器的文件名称
String fileName=item.getOriginalFilename();
if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
//03.路径拼接
File file = new File(path,fileName);
item.transferTo(file);
}
return "welcome.jsp";
}
}
return "error.jsp";
}

文件下载

@RequestMapping(value="/first.do")
 public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType
) throws Exception { request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null; //获取项目根目录
String ctxPath = request.getSession().getServletContext()
.getRealPath(""); //获取下载文件露肩
String downLoadPath = ctxPath+"/uploadFile/"+ storeName; //获取文件的长度
long fileLength = new File(downLoadPath).length(); //设置文件输出类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(storeName.getBytes("utf-8"), "ISO8859-1"));
//设置输出长度
response.setHeader("Content-Length", String.valueOf(fileLength));
//获取输入流
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
//输出流
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
//关闭流
bis.close();
bos.close();
}

下载直接访问控制器如:http:\\localhost:8080/springmvc/download.do

或者通过JSP页面

<a href="./downloadFile/download" >下载</a>

  

文件上传(StringMVC)的更多相关文章

  1. jquery.uploadify文件上传组件

    1.jquery.uploadify简介 在ASP.NET中上传的控件有很多,比如.NET自带的FileUpload,以及SWFUpload,Uploadify等等,尤其后面两个控件的用户体验比较好, ...

  2. 11、Struts2 的文件上传和下载

    文件上传 表单准备 要想使用 HTML 表单上传一个或多个文件 须把 HTML 表单的 enctype 属性设置为 multipart/form-data 须把 HTML 表单的method 属性设置 ...

  3. Java FtpClient 实现文件上传服务

    一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...

  4. 小兔Java教程 - 三分钟学会Java文件上传

    今天群里正好有人问起了Java文件上传的事情,本来这是Java里面的知识点,而我目前最主要的精力还是放在了JS的部分.不过反正也不麻烦,我就专门开一贴来聊聊Java文件上传的基本实现方法吧. 话不多说 ...

  5. ,net core mvc 文件上传

    工作用到文件上传的功能,在这个分享下 ~~ Controller: public class PictureController : Controller { private IHostingEnvi ...

  6. Web开发安全之文件上传安全

    很长一段时间像我这种菜鸡搞一个网站第一时间反应就是找上传,找上传.借此机会把文件上传的安全问题总结一下. 首先看一下DVWA给出的Impossible级别的完整代码: <?php if( iss ...

  7. AutoIt实现Webdriver自动化测试文件上传

    在运用WebDriver进行自动化测试时,由于WebDriver自身的限制,对于上传文件时Windows弹出的文件选择窗口无法控制,通过在网上查找资料锁定使用AutoIt来控制文件上传窗口. Auto ...

  8. Struts的文件上传下载

    Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...

  9. .JavaWeb文件上传和FileUpload组件使用

    .JavaWeb文件上传 1.自定义上传 文件上传时的表单设计要符合文件提交的方式: 1.提交方式:post 2.表单中有文件上传的表单项:<input type="file" ...

随机推荐

  1. Agent Job相关的系统表

    参考: http://www.cnblogs.com/CareySon/p/5262311.html msdb中,有三张与Agent Job相关的系统表,需要了解一下 msdb.dbo.sysjobs ...

  2. python学习——读取染色体长度(五:从命令行输入染色体长度)

    # 传递命令行参数 # 导入sys模块 import sys print(sys.argv)   命令行操作 python argv.py 10 20 30 40 50 回车输出 ['argv.py' ...

  3. redis编译 报告错误 jemalloc/jemalloc.h:没有那个文件或目录 解决.

    问题原因:没找到jemalloc头文件. 百度谷歌半天没找到有效的下载地址. github中有 到github下载.jemalloc https://github.com/jemalloc/jemal ...

  4. 注意:QQ影音视频压缩时长丢失

    客户宣传片发来,高清的,比较大,500多M,需要转成小一点的,放在客户网站上,于是用QQ影音转码压缩下,变成低质量的.如下 一切都很顺利,提示进度100%! 这一切都是电脑自动的,又是提示成功的,千想 ...

  5. redis 连接idea一直被拒绝

    网上查找的方法 方法一:idea中已经下载了Iedis 插件, 也导入了jar包 <!-- https://mvnrepository.com/artifact/commons-pool/com ...

  6. springboot实现简单的文件上传

    承接上一篇,这里记录一下简单的springboot文件上传的方式 首先,springboot简单文件上传不需要添加额外的jar包和配置 这里贴一下后端controller层的实现代码 补一份前台的HT ...

  7. Kafka概述(一)

    一.消息队列 客户端A给客户端B发送数据,若是直接发的话,客户端A给客户端B需要同步. 例如, 1)  A在给B发送数据的时候,B挂掉了,此时的A是没有办法给B发送数据的: 2)  A发送10M/s, ...

  8. DNS预解析prefetch

    前面的话 本文将详细介绍DNS预解析prefetch的主要内容 概述 DNS(Domain Name System, 域名系统),是域名和IP地址相互映射的一个分布式数据库.DNS 查询就是将域名转换 ...

  9. python+ffmpeg切割视频

    什么是ffmpeg 1.1 简介 FFmpeg是一个开源免费跨平台的视频和音频流方案,属于自由软件,采用LGPL或GPL许可证(依据你选择的组件).它提供了录制.转换以及流化音视频的完整解决方案.它包 ...

  10. git只追踪特定类型的文件

    比如我只关心所有office文档并排除掉~开头的辅助文件: * !*/ !*.docx !*.doc !*.xlsx ~*