上传:

  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. Kickstart无人值守原理及简介

    原文转自:https://www.cnblogs.com/itzgr/p/10029461.html作者:木二 目录 一 简介及原理 二 搭建无人值守步骤 三 PXE介绍 四 Kickstart简介 ...

  2. Spring BeanDefinition

    定义 /** * A BeanDefinition describes a bean instance, which has property values, * constructor argume ...

  3. Java并发之Synchronized机制详解

    带着问题阅读 1.Synchronized如何使用,加锁的粒度分别是什么 2.Synchronized的实现机制是什么 3.Synchronized是公平锁吗 4.Java对Synchronized做 ...

  4. shell脚本中的多行注释

    shell 中注释的使用方法 1. 单行注释 单行注释最为常见,它是通过一个'#'来实现的.注意shell脚本的最开始部分"#!/bin/bash"的#号不是用来注释的. 2. 多 ...

  5. GIT:修改上一次提交的注释信息(git commit --amend)

    git commit -m 注释信息 如果这时候注释信息输入错误,就可以输入以下指令更改 git commit --amend 键入" i "进入编辑模式 修改后键入ESC,:wq ...

  6. [推荐]MyBatis 核心技术与面试 34 讲

    MyBatis 核心技术与面试 34 讲 职业生涯中常被问到: 如何成为某方面的高手? 如何快速搞定某项技术? 我现在的水平处于什么阶段? -- 我暗暗想,我们从小学到中学到大学,经历了大考三六九.小 ...

  7. CodeForce-799C Fountains (记忆化DP)

    Fountains CodeForces - 799C 某土豪想要造两座喷泉.现在有 n 个造喷泉的方案,我们已知每个方案的价格以及美观度.有两种合法的货币:金币和钻石.这两种货币之间不能以任何方式转 ...

  8. C#导出数据—使用Word模板

    前言 本文主要介绍C#使用标签替换的方法导出数据,导出的数据模板使用Word文档. 模板建立 首先创建一个Word文档,然后建立一个基础模板.然后将上方菜单切换到插入菜单. 然后在想填充数据的地方添加 ...

  9. Apache设置禁止访问网站目录

    使用Apache作为Web服务器的时候,在当前目录下没有index.html|php等入口就会显示目录.让目录暴露在外面是非常危险的事. 找到Apache的配置文件 /etc/apache2/apac ...

  10. ecshop二次开发秒杀、限时折扣、清仓等功能

    限时抢购,秒杀商品的二次开发 1,先在后台admin/templates 中找goods_info.htm文件到促销部分,改为一个下拉列表的分别是促销,限时,秒杀,值分别是1,2,3这样,代码如下: ...