Spring 中的文件上传与下载控制
- 先创建根应用上下文配置,WebDemo/src/main/java/com/seliote/webdemo/config/RootContextConfig.java
package com.seliote.webdemo.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
// 配置类必须标注 @Configuration 注解
@Configuration
// 设置注解扫描,默认扫描所有标注了 @Component 的类(@Component 标注的标注也算),都将变为 Spring 管理的 bean(自动实例化与注入依赖)
@ComponentScan(
// 注解扫描的起始包
basePackages = "com.seliote.webdemo",
// 排除对标注了 @Configuration 与 @Controller 类的实例化
excludeFilters = @ComponentScan.Filter({Configuration.class, Controller.class})
)
public class RootContextConfig {
}
- 创建 Servlet 上下文配置,注意其中注册了一个 MultipartResolver 用于 Servlet 3.0- 的文件下载,WebDemo/src/main/java/com/seliote/webdemo/config/ServletContextConfig.java
package com.seliote.webdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
// 激活注解驱动的控制器请求映射
@EnableWebMvc
@ComponentScan(
basePackages = "com.seliote.webdemo",
// 忽略默认扫描模式
useDefaultFilters = false,
// 仅对标注了 @Controller 的类进行扫描
includeFilters = @ComponentScan.Filter(Controller.class)
)
public class ServletContextConfig {
// 启用文件上传,如果不是 Servlet 3.0+ 就使用第三方工具
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
- 编写启动项,注意其中注册 DispatcherServlet 时所调用的
dynamic.setMultipartConfig(new MultipartConfigElement(...))方法用于开启文件上传,WebDemo/src/main/java/com/seliote/webdemo/config/Bootstrap.java
package com.seliote.webdemo.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
// ServletContainerInitializer 接口的实现将在应用程序启动时(所有监听器启动之前)调用 onStartup() 方法(应用可用的最早时间点),
// 但是直接实现 ServletContainerInitializer 过于麻烦,所以提供了一个 SpringServletContainerInitializer 桥接口,
// 它会在应用程序启动时扫描应用中所有 WebApplicationInitializer 接口的实现并调用其 onStartup() 方法
public class Bootstrap implements WebApplicationInitializer {
public void onStartup(ServletContext aServletContext) throws ServletException {
// 允许 Servlet 容器提供静态文件
aServletContext.getServletRegistration("default").addMapping("/resource/*");
// 配置根应用上下文
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfig.class);
// 通过监听器启动根上下文(ContextLoaderListener 将在 Web 应用程序启动时初始化
aServletContext.addListener(new ContextLoaderListener(rootContext));
// 配置 Servlet 上下文
AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext();
servletContext.register(ServletContextConfig.class);
// 动态注册一个 DispatcherServlet,注意是 new DispatcherServlet(ApplicationContext)
// 并传入上文创建的 AnnotationConfigWebApplicationContext,而非传入 DispatcherServlet.class
ServletRegistration.Dynamic dynamic = aServletContext.addServlet("dispatcherServlet", new DispatcherServlet(servletContext));
// 启用文件上传
dynamic.setMultipartConfig(new MultipartConfigElement("/tmp", 20_971_520L, 41_943_040L, 512_000));
// 设置 DispatcherServlet 的映射
dynamic.addMapping("/");
// 设置应用程序部署后即启动
dynamic.setLoadOnStartup(1);
}
}
- 两个 JSP 用于上传和下载
WebDemo/web/upload.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" language="java" %>
<html>
<head>
<title>Upload</title>
</head>
<body>
<h2>Select a file:</h2><br /><br />
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="userFile" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
WebDemo/web/download.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" language="java" %>
<html>
<head>
<title>Download</title>
</head>
<body>
<a href="/download">
<button type="button">Download</button>
</a>
</body>
</html>
- 最后编写控制器即可,WebDemo/src/main/java/com/seliote/webdemo/controller/FileController.java
package com.seliote.webdemo.controller;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class FileController {
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@RequestMapping("/upload")
public String upload(@RequestPart("userFile") Part aPart) throws IOException {
if (aPart == null) {
return "Part is null";
}
InputStream inputStream = aPart.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readLength = -1;
while ((readLength = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, readLength);
}
int length = byteArrayOutputStream.size();
byteArrayOutputStream.close();
return "Success!" + length;
}
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@RequestMapping("/download")
public void download(HttpServletRequest aHttpServletRequest, HttpServletResponse aHttpServletResponse) throws IOException {
File file = new File("/home/seliote/Temp/grub.cfg");
// 设置响应头,说明是文件下载
aHttpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
aHttpServletResponse.setContentType("application/octet-stream");
// 为响应手动写入文件
InputStream inputStream = new FileInputStream(file);
ServletOutputStream servletOutputStream = aHttpServletResponse.getOutputStream();
byte[] buffer = new byte[1024];
int readLength = -1;
while ((readLength = inputStream.read(buffer)) != -1) {
servletOutputStream.write(buffer, 0, readLength);
}
inputStream.close();
}
}
Spring 中的文件上传与下载控制的更多相关文章
- Java Web 学习(8) —— Spring MVC 之文件上传与下载
Spring MVC 之文件上传与下载 上传文件 表单: <form action="upload" enctype="multipart/form-data&qu ...
- javaWeb中,文件上传和下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- JavaWeb中的文件上传和下载功能的实现
导入相关支持jar包:commons-fileupload.jar,commons-io.jar 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上 ...
- Spring MVC的文件上传和下载
简介: Spring MVC为文件上传提供了直接的支持,这种支持使用即插即用的MultipartResolver实现的.Spring MVC 使用Apache Commons FileUpload技术 ...
- 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity
文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...
- Spring MVC-学习笔记(5)spring MVC的文件上传、下载、拦截器
1.文件上传. spring MVC为文件上传提供了直接的支持,这种支持是即插即用的MultipartResolver(多部分解析器)实现的.spring MVC使用Apache Commo ...
- 使用Spring MVC实现文件上传与下载
前段时间做毕业设计的时候,想要完成一个上传文件的功能,后来,虽然在自己本地搭建了一个ftp服务器,然后使用公司的工具完成了一个文档管理系统:但是还是没有找到自己想要的文件上传与下载的方式. 今天看到一 ...
- Spring Boot入门——文件上传与下载
1.在pom.xml文件中添加依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- Java中的文件上传和下载
文件上传原理: 早期的文件上传机制: 在TCP/IP中.最早出现的文件上传机制是FTP.他是将文件由客户端发送到服务器的标准机制. jsp中的文件上传机制: 在jsp编程中不能使用FTP的方法来上传文 ...
随机推荐
- PHP:使用php,循环html中的select标签与Php数据
select标签,我们都知道是下拉列表,这里,我们使用foreach循环,将select中的数据进行输出 例子: 1.数据表:mimi_article,表中有个字段,为1或0,表示着是或否 2.通过p ...
- react-webpack-express
这是一个整合react express 实现前后台交互,并且采用webpack进行打包和解析文件.其实react官方有一个脚手架create react app,也可以看那个,但是这个脚手架webpa ...
- 使用Cloud application Studio在C4C UI里创建下拉列表(dropdown list)
在Cloud Application Studio里新建一个Code List Data Type: 维护Value和描述信息,以及在ABSL里使用的constant值. 保存之后,上述维护的信息会存 ...
- 使用 Android 客户端向 Ruby on rails 构建的 Web Application 提交 HTTP GET 和 HTTP POST 请求
最近想弄个能访问 Internet 的 Android 应用,因为求快所以用了 Ruby on Rails 来提供 HTTP 资源.这方面的资料还是比较少的,所以把尝试的过程记录下来. 1 使用 Ru ...
- luogu P1768 天路
嘟嘟嘟 01分数规划之最优比率环. 主要是发一下基于dfs的spfa.跑的贼快,原来总用时2000多ms还TLE了两个点,改成dfs后总用时直降43ms! #include<cstdio> ...
- 整个ssd的网络和multibox_loss_layer
总结说来prior_box层只完成了一个提取anchor的过程,其他与gt的match,筛选正负样本比例都是在multibox_loss_layer完成的 http://www.360doc.com/ ...
- vue---组件引入及使用的几种方式
在vue的项目开发过程中,基本都是基于组件化开发项目,总结下使用组件的几个点: 一.@符号的使用 在vue项目中 @ 符号代表的是根目录,即 src 目录. 二.组件的放置位置 在项目中,公用的组件放 ...
- 【luogu P3384 树链剖分】 模板
题目链接:https://www.luogu.org/problemnew/show/P3384 诶又给自己留了个坑..不想写线段树一大理由之前的模板变量名太长 #include <cstdio ...
- 【luogu P1144 最短路计数】 题解
题目链接:https://www.luogu.org/problemnew/show/P1144 #include <iostream> #include <cstdio> # ...
- WSASocket()与Socket()的区别 转
/**************************************************** WSASocket是Windows专用,支持异步操作:socket是unix标准,只能同步操 ...