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

首先准备好一个页面

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. Excel自定义公式,类似VLOOKUP的查询

    Excel在使用VLOOKUP时,当检索值超过255长度的时候就会报错,没法正常检索. 官方提供的办法是通过INDEX和MATCH公式组合使用来解决. 微软官方方案 1,公式 =INDEX($A$5: ...

  2. selenium之元素定位-xpath

    被测试网页的HTML代码 <html> <body> <div id="div1" style="text-align:center&quo ...

  3. 怪事年年有,今天特别多!org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'empno' not found. Available parameters are [emp, deptno, param1, param

    错误: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.Binding ...

  4. 什么是 CI/CD?

    什么是 CI/CD? 在软件开发中经常会提到持续集成Continuous Integration(CI)和持续交付Continuous Delivery(CD)这几个术语.但它们真正的意思是什么呢? ...

  5. 【vue】iView-admin2.0动态菜单路由

    vue项目实现动态路由有俩种方式 一.前端在routers中写好--所有--路由表 <前端控制路由>,登录时根据用户的角色权限来动态的显示菜单路由 二.前端通过调用接口请求拿到当前用户-- ...

  6. 分布式存储ceph——(6)ceph 讲解

    一.Ceph简介: Ceph是一种为优秀的性能.可靠性和可扩展性而设计的统一的.分布式文件系统.ceph 的统一体现在可以提供文件系统.块存储和对象存储,分布式体现在可以动态扩展.在国内一些公司的云环 ...

  7. (light oj 1024) Eid (最小公倍数)

    题目链接: http://lightoj.com/volume_showproblem.php?problem=1024 In a strange planet there are n races. ...

  8. 译注(2): How to Write a 21st Century Proof

    原文:Computer Scientist Tells Mathematicians How To Write Proofs 对比一下下面两个证明哪个更好? 版本一: "A square a ...

  9. Linux调整日期时间

    Linux日期不准确,要更改 Linux 系统整个系统范围的时区可以使用如下命令: sudo rm -f /etc/localtime sudo ln -s /usr/share/zoneinfo/A ...

  10. git版本回退

    场景1: 当你改乱了工作区某个文件的内容,修改后未执行git add和git commit,想直接丢弃工作区的修改时,用命令git checkout -- file. 场景2: 当你不但改乱了工作区某 ...