上传:

  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 }

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

  1. myBatis + SpringMVC上传、下载文件

    摘自: http://limingnihao.iteye.com/blog/1069503 环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何 ...

  2. vue+springboot上传和下载附件功能

    https://blog.csdn.net/qq_35867245/article/details/84325385 上传附件(服务端代码) 第一步:在application.yml中配置附件要上传的 ...

  3. angularjs + springmvc 上传和下载

    jsp: <form ng-submit="uploadFile()" class="form-horizontal" enctype="mul ...

  4. springmvc上传,下载

    参考: 上传: 如下代码,可将上传内容复制到上传地址 file.transferTo(new File(realPath + File.separator + realName)); http://b ...

  5. SpringMVC上传下载

    springmvc上传和下载功能 写在一个简单的示例在线基准码 1.导入的必要性jar包:ant.jar.commons-fileupload.jar.connom-io.jar. 当然spring ...

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

    目录 1. 准备工作 1.1 数据库表准备 1.2 实体类 User 和 Mapper(DAO) 1.3 pom.xml 依赖包 1.4 SSM 框架的整合配置 2. 控制器 UserControll ...

  7. SpringMVC文件上传和下载

    上传与下载 1文件上传 1.1加入jar包 文件上传需要依赖的jar包 1.2配置部件解析器 解析二进制流数据. <?xml version="1.0" encoding=& ...

  8. 使用SpringMVC框架实现文件上传和下载功能

    使用SpringMVC框架实现文件上传和下载功能 (一)单个文件上传 ①配置文件上传解释器 <!—配置文件上传解释器 --> <mvc:annotation-driven>&l ...

  9. 基于SpringMVC的文件(增删改查)上传、下载、更新、删除

    一.项目背景 摘要:最近一直在忙着项目的事,3个项目过去了,发现有一个共同的业务,那就是附件的处理,附件包括各种文档,当然还有图片等特殊文件,由于时间的关系,每次都是匆匆忙忙的搞定上线,称这项目的空档 ...

随机推荐

  1. nginx 开启,关闭,重启

    2021-08-191. 启动 # 判断配置文件是否正确 cd /usr/local/nginx/sbin ./nginx -t # 启动 cd usr/local/nginx/sbin ./ngin ...

  2. Python中管理数据库

    前言:Python中是利用MySQL模块和数据库之间建立联系. MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL ...

  3. Nginx的高级使用

    1.概述 之前介绍过Nginx的简单使用,今天来聊聊Nginx的一些高级使用. 2.使用Nginx解决跨域问题 当公司存在多个域名时,两个不同的域名相互访问就会存在跨域问题. 或者在进行前端开发时,通 ...

  4. (四)羽夏看C语言——循环与跳转

    写在前面   由于此系列是本人一个字一个字码出来的,包括示例和实验截图.本人非计算机专业,可能对本教程涉及的事物没有了解的足够深入,如有错误,欢迎批评指正. 如有好的建议,欢迎反馈.码字不易,如果本篇 ...

  5. MyBatis学习总结(六)——Mybatis3.x与Spring4.x整合

    一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype:create -DgroupId=me.gacl -DartifactId=spring4-myba ...

  6. Linux下用Sed查找IP地址

    ip addr|sed -n '9p'|egrep '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'|sed -nr 's#^.*inet (.*) b ...

  7. [考试总结]noip模拟44

    这个真的是一个 \(nb\) 题. 考试快要结束的时候,在机房中只能听到此起彼伏的撕吼. 啊---------- 然后人们预测这自己的得分. \(\color{red}{\huge{0}}\) \(\ ...

  8. Spring Boot学习(一)——Spring Boot介绍

    Spring Boot介绍 Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式 ...

  9. 类型定义VS类型别名

    类型定义是在当前包中的一直存在的.输出%T,发现类型前面都有main.前缀 类型别名,其实还是它的根本类型,别名只存在在代码中.编译后就不存在了,还是根本类型.

  10. Linux find命令实例教程 15个find命令用法

    除了在一个目录结构下查找文件这种基本的操作,你还可以用find命令实现一些实用的操作,使你的命令行之旅更加简易.本文将介绍15种无论是于新手还是老鸟都非常有用的Linux find命令.首先,在你的h ...