springMVC上传和下载附件
上传:
导入需要的jar包:Spring MVC类库 + 文件上传下载需要的JAR包,图中A处为文件上传下载需要的JAR包,其余为Spring MVC类库。
- 构建领域模层: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 }
设置上传页面upload的表单
- 配置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上传和下载附件的更多相关文章
- myBatis + SpringMVC上传、下载文件
摘自: http://limingnihao.iteye.com/blog/1069503 环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何 ...
- vue+springboot上传和下载附件功能
https://blog.csdn.net/qq_35867245/article/details/84325385 上传附件(服务端代码) 第一步:在application.yml中配置附件要上传的 ...
- angularjs + springmvc 上传和下载
jsp: <form ng-submit="uploadFile()" class="form-horizontal" enctype="mul ...
- springmvc上传,下载
参考: 上传: 如下代码,可将上传内容复制到上传地址 file.transferTo(new File(realPath + File.separator + realName)); http://b ...
- SpringMVC上传下载
springmvc上传和下载功能 写在一个简单的示例在线基准码 1.导入的必要性jar包:ant.jar.commons-fileupload.jar.connom-io.jar. 当然spring ...
- Spring MVC 上传、下载、显示图片
目录 1. 准备工作 1.1 数据库表准备 1.2 实体类 User 和 Mapper(DAO) 1.3 pom.xml 依赖包 1.4 SSM 框架的整合配置 2. 控制器 UserControll ...
- SpringMVC文件上传和下载
上传与下载 1文件上传 1.1加入jar包 文件上传需要依赖的jar包 1.2配置部件解析器 解析二进制流数据. <?xml version="1.0" encoding=& ...
- 使用SpringMVC框架实现文件上传和下载功能
使用SpringMVC框架实现文件上传和下载功能 (一)单个文件上传 ①配置文件上传解释器 <!—配置文件上传解释器 --> <mvc:annotation-driven>&l ...
- 基于SpringMVC的文件(增删改查)上传、下载、更新、删除
一.项目背景 摘要:最近一直在忙着项目的事,3个项目过去了,发现有一个共同的业务,那就是附件的处理,附件包括各种文档,当然还有图片等特殊文件,由于时间的关系,每次都是匆匆忙忙的搞定上线,称这项目的空档 ...
随机推荐
- netty系列之:自建客户端和HTTP服务器交互
目录 简介 使用客户端构建请求 accept-encoding server解析HTTP请求 总结 简介 上一篇文章,我们搭建了一个支持中文的HTTP服务器,并且能够从浏览器访问,并获取到相应的结果. ...
- 剑指 Offer 32 - I. 从上到下打印二叉树
剑指 Offer 32 - I. 从上到下打印二叉树 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印. 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 ...
- 简单三分钟,本地搭建 k8s
使用 minikube 在本地搭建 k8s 已经比以前要简单很多了.本文,我们通过简短的三分钟来重现一下在本地搭建 k8s 实验环境的步骤. Newbe.Claptrap 是一个用于轻松应对并发问题的 ...
- CentOS管理firewalld防火墙
1.查看防火墙某个端口是否开放 firewall-cmd --query-port=80/tcp 2.开放防火墙端口80 firewall-cmd --zone=public --add-port=8 ...
- noip模拟29
这次终于是早上考试了 早上考试手感不错,这次刷新了以前的最高排名- %%%cyh巨佬 \(rk1\) %%%CT巨佬 \(t2\) 90 纵观前几,似乎我 \(t3\) 是最低的-- 总计挂分10分, ...
- 学了这么多年C语言,你真的知道全局变量,局部变量,静态变量,本地函数,外部函数是如何区分标识的吗?
动态库内容分析 文章目录 动态库内容分析 1. 动态库编译 1.1 第一个C文件:basic.c 1.2第二个C文件:demo.c 1.3第三个C文件:main.c 2.动态库编译 3.二进制内容分析 ...
- 不写注释的程序员-Models
Models 不写注释的程序员-Models # This is an auto-generated Django model module. # You'll have to do the foll ...
- 远程线程注入DLL突破session 0 隔离
远程线程注入DLL突破session 0 隔离 0x00 前言 补充上篇的远程线程注入,突破系统SESSION 0 隔离,向系统服务进程中注入DLL. 0x01 介绍 通过CreateRemoteTh ...
- 10 个不为人知的Python冷知识
1. 省略号也是对象 ... 这是省略号,在Python中,一切皆对象.它也不例外. 在 Python 中,它叫做 Ellipsis . 在 Python 3 中你可以直接写-来得到这玩意. > ...
- Windows 10 之 WSL 2
Windows Subsystem for Linux(WSL)无疑大大提升了Windows下程序开发的体验. WSL 2向开发者提供的完整的系统调用兼容,使得许多无法在WSL 1中安装的应用,如Do ...