springMVC上传和下载附件

上传:

  1. 导入需要的jar包:Spring MVC类库 + 文件上传下载需要的JAR包,图中A处为文件上传下载需要的JAR包,其余为Spring MVC类库。

  1. 构建领域模层:model层和control层、view层

FileController:

 1 package com.controller.system;
 2
 3 import java.io.FileOutputStream;
 4 import java.io.OutputStream;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11
12 import org.springframework.stereotype.Controller;
13 import org.springframework.ui.Model;
14 import org.springframework.web.bind.annotation.RequestMapping;
15 import org.springframework.web.bind.annotation.RequestMethod;
16 import org.springframework.web.multipart.MultipartHttpServletRequest;
17 import org.springframework.web.multipart.commons.CommonsMultipartFile;
18
19 import com.model.system.MyFile;
20
21 @Controller
22 @RequestMapping("fileController")
23 public class FileController {
24
25     @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
26     public String upload(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model,MyFile myFile) {
27
28         try {
29             // 1. 转化request
30             MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
31             // 2. /获得文件
32             CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("myUpFile");//myUpFile前端页面输入附件处input的name
33             // 3. 获得文件的字节数组
34             byte[] bytefile = cfile.getBytes();
35             // 4. 获得文件后缀名
36             String oldName = cfile.getOriginalFilename();
37             // 截取后缀名
38             String suffix = oldName.substring(oldName.lastIndexOf("."));
39             // 5. 获取项目的路径
40             String path = request.getSession().getServletContext().getRealPath("/");
41             // 6. 定义OutputStream
42             // 设置文件名:取当前时间
43             Date date = new Date();
44             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
45             String filename = sdf.format(date);
46
47             String url = "\\G:\\upanddown\\upfile\\" + filename + suffix;
48             System.out.println(url);
49             OutputStream os = new FileOutputStream(url);
50
51             os.write(bytefile);
52             // 7.关闭资源
53             os.flush();
54             os.close();
55         } catch (Exception e) {
56             e.printStackTrace();
57         }
58         return "upload";
59
60     }
61 }

MyFile

 1 package com.model.system;
 2
 3 public class MyFile {
 4
 5     private String fileUserName;
 6     private String url;
 7
 8
 9     public MyFile() {}
10
11     public MyFile(String fileUserName, String url) {
12         super();
13         this.fileUserName = fileUserName;
14         this.url = url;
15     }
16
17     public String getFileUserName() {
18         return fileUserName;
19     }
20
21     public void setFileUserName(String fileUserName) {
22         this.fileUserName = fileUserName;
23     }
24
25     public String getUrl() {
26         return url;
27     }
28
29     public void setUrl(String url) {
30         this.url = url;
31     }
32
33     @Override
34     public String toString() {
35         return "MyFile [fileUserName=" + fileUserName + ", url=" + url + "]";
36     }
37
38
39 }
  1. 设置上传页面upload的表单

  1. 配置web.xml和dispatcher-servlet.xml

web.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 3   <display-name>springMvc_upload</display-name>
 4   <servlet>
 5     <servlet-name>dispatcher</servlet-name>
 6     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 7   </servlet>
 8   <servlet-mapping>
 9     <servlet-name>dispatcher</servlet-name>
10     <url-pattern>*.do</url-pattern>
11   </servlet-mapping>
12   <filter>
13     <filter-name>CharacterEncodingFilter</filter-name>
14     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
15     <init-param>
16       <param-name>encoding</param-name>
17       <param-value>UTF-8</param-value>
18     </init-param>
19   </filter>
20   <filter-mapping>
21     <filter-name>CharacterEncodingFilter</filter-name>
22     <url-pattern>/*</url-pattern>
23   </filter-mapping>
24   <welcome-file-list>
25     <welcome-file>upload.jsp</welcome-file>
26   </welcome-file-list>
27 </web-app>

dispatcher-servlet.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 8 http://www.springframework.org/schema/mvc
 9 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
10 http://www.springframework.org/schema/context
11 http://www.springframework.org/schema/context/spring-context-3.0.xsd
12 http://www.springframework.org/schema/aop
13 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
14 http://www.springframework.org/schema/tx
15 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
16
17     <!-- 注解驱动 -->
18     <mvc:annotation-driven />
19     <!-- springMVC扫描驱动 -->
20     <context:component-scan base-package="com.controller.*"></context:component-scan>
21
22     <!-- 配置试图解析器 -->
23     <bean
24         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
25         <property name="prefix" value="/"></property>
26         <property name="suffix" value=".jsp"></property>
27     </bean>
28
29     <!-- 从请求和响应读取/编写字符串 -->
30     <bean id="stringConverter"
31         class="org.springframework.http.converter.StringHttpMessageConverter">
32         <property name="supportedMediaTypes">
33             <list>
34                 <value>text/plain;charset=UTF-8</value>
35             </list>
36         </property>
37     </bean>
38
39     <!-- 用于将对象转换为 JSON -->
40     <bean id="jsonConverter"
41         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
42     <bean
43         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
44         <property name="messageConverters">
45             <list>
46                 <ref bean="stringConverter" />
47                 <ref bean="jsonConverter" />
48             </list>
49         </property>
50     </bean>
51
52     <!-- 上传下载配置 -->
53     <bean id="multipartResolver"
54         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
55         <!-- maxUploadSize:文件上传的最大值以byte为单位 -->
56         <property name="maxUploadSize" value="1024000"></property>
57     </bean>
58
59
60 </beans>

下载:

配置和上面的一样(用同一个项目),在view层中编码如下,用来下载:

1 <body>
2     <h1>文件中心</h1>
3     ${myFile}
4     <a href="<%=basePath%>fileController/download.do?url=${myFile.url}" >下载</a>
5 </body>

FileController:中添加下载方法:

 1 /**
 2      * 下载文件
 3      * @throws IOException
 4      */
 5
 6     @RequestMapping(value = "/download.do")
 7     public void download(HttpServletRequest request,HttpServletResponse response, String url) throws IOException {
 8         String strUrl = url;
 9
10         // 截取字符串
11         int i = 29;
12         String urlstr = url.substring(i);
13         System.out.println("#########################___" + urlstr);
14
15         // 获取输入流
16         InputStream bis = new BufferedInputStream(new FileInputStream(new File(
17                 strUrl)));
18         // 假如以中文名下载的话
19         String filename = urlstr;
20         // 转码,免得文件名中文乱码
21         filename = URLEncoder.encode(filename, "UTF-8");
22         // 设置文件下载头
23         response.addHeader("Content-Disposition", "attachment;filename="
24                 + filename);
25         // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
26         response.setContentType("multipart/form-data");
27         BufferedOutputStream out = new BufferedOutputStream(
28                 response.getOutputStream());
29         int len = 0;
30         while ((len = bis.read()) != -1) {
31             out.write(len);
32             out.flush();
33         }
34         out.close();
35     }

原文地址:https://www.cnblogs.com/ynhwl/p/9649472.html

时间: 2024-07-31 13:49:13

springMVC上传和下载附件的相关文章

上传和下载附件功能

HTML上传部分 文件名:<asp:TextBox ID="tbFileName" runat="server" Width="150px"></asp:TextBox>文件(80M以内): <asp:FileUpload ID="FileUpload2" runat="server" /> <asp:Button ID="Button1" ru

springMVC上传与下载

springMVC上传与下载 首先,springmvc.xml必须配置: Java代码 1.      <bean id="multipartResolver" 2.              class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/> <bean id="m

myBatis + SpringMVC上传、下载文件

环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中:如何从数据库下载文件,和显示图像文件并实现缩放. 将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob. 首先要创建数据库,此处使用MySql数据库. 注意:文中给出的代码多为节选重要片段,并不齐全. 1.  前期准备 使用maven创建一个springMVC+spring+mybatis+mysql的项

转载:SpringMVC:上传与下载

1 springmvc.xml必须配置: Java代码   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/> Java代码   <bean id="multipartResolver" class=

angularjs + springmvc 上传和下载

jsp: <form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data"> <input type="file" name="file" ng-model="document.fileInput" id="file" onchange="

Spring MVC 上传、下载、显示图片

通过这篇文章你可以了解到: 使用 SpringMVC 框架,上传图片,并将上传的图片保存到文件系统,并将图片路径持久化到数据库 在 JSP 页面上实现显示图片.下载图片 [TOC] 1. 准备工作 首先我们需要准备好开发环境,本文测试环境是 SSM(Spring 4.3.9 + SpringMVC 4.3.9 + MyBatis 3.4.4) ,数据库为 MySQL 5.5,数据库连接池 C3P0 0.9.5.2,构建包 Maven 3.5.0,Tomcat 8.5. 限于篇幅原因,关于 SSM

springmvc和servlet下的文件上传和下载(存文件目录和存数据库Blob两种方式)

项目中涉及了文件的上传和下载,以前在struts2下做过,今天又用springmvc做了一遍,发现springmvc封装的特别好,基本不用几行代码就完成了,下面把代码贴出来: FileUpAndDown.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"%> <html> <head> <title>using commons Uplo

springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)

参与该项目的文件上传和下载.一旦struts2下完成,今天springmvc再来一遍.发现springmvc特别好包,基本上不具备的几行代码即可完成,下面的代码贴: FileUpAndDown.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"%> <html> <head> <title>using commons Upload to

SpringMVC实现文件的上传和下载

前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:"用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流".我回复他说:"使用SpringMVC框架可以做到这一点,因为SpringMVC为文件的上传提供了直接的支持,但需要依赖Apache提供Commons FileUpload组件jar包."鉴于这个问题,我上网也百度了一下,网上很多都是介绍的使用IO流来实现文件的上传和下载,也有说到框架的,但介绍的并不是很完整,今天小钱将和大家介绍使用Spr