Spring boot实现文件上传功能
作者:卡通人物nnn 发布时间:2023-08-01 07:00:02
标签:Spring,boot,文件上传
本文实例为大家分享了Spring boot实现文件上传的具体代码,供大家参考,具体内容如下
1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
2. 在webapp目录下的index.jsp文件中输入一个表单:
<html>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">
File to upload: <input type="file" name="file"><br />
Name: <input type="text" name="name"><br /> <br />
<input type="submit" value="Upload">
Press here to upload the file!
</form>
</body>
这个表单就是我们模拟的上传页面
3. 编写处理这个表单的Controller:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@RequestMapping(value="/upload", method=RequestMethod.GET)
public @ResponseBody String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
}
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
}
4. 然后我们对上传的文件做一些限制,同时编写main方法来启动这个web :
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.MultiPartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultiPartConfigFactory factory = new MultiPartConfigFactory();
factory.setMaxFileSize("128KB");
factory.setMaxRequestSize("128KB");
return factory.createMultipartConfig();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. 然后访问http://localhost:8080/upload就可以看到页面了。
上面的例子是实现的是单个文件上传的功能,假定我们现在要实现文件批量上传的功能的话,我们只需要简单的修改一下上面的代码就行,考虑到篇幅的问题,下面只是贴出和上面不同的代码,没有贴出的说明和上面一样。:
1.新增batchUpload.jsp文件
<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="/batch/upload">
File to upload: <input type="file" name="file"><br />
File to upload: <input type="file" name="file"><br />
<input type="submit" value="Upload"> Press here to upload the file!
</form>
</body>
</html>
2. 新增BatchFileUploadController.java文件:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
/**
* Created by wenchao.ren on 2014/4/26.
*/
@Controller
public class BatchFileUploadController {
@RequestMapping(value="/batch/upload", method= RequestMethod.POST)
public @ResponseBody
String handleFileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
for (int i =0; i< files.size(); ++i) {
MultipartFile file = files.get(i);
String name = file.getName();
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + i)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
return "upload successful";
}
}
这样一个简单的批量上传文件的功能就ok了,是不是很简单啊。
注意:上面的代码只是为了演示而已,所以编码风格上采取了随性的方式,不建议大家模仿。
参考资料:MultipartResolver实现文件上传功能
1. MultipartResolver也可以实现文件上传功能。参考文章:
来源:https://blog.csdn.net/woshizhangliang999/article/details/46711747


猜你喜欢
- 一款书籍阅读器,需要以下功能才能说的上比较完整:文字页面展示,即书页;页面之间的跳转动画,即翻页动作;能够在每一页上记录阅读进度,即书签;能
- 一、前言TreeView这个控件对于我来说是用得比较多的,以前做的小聊天软件(好友列表)、音乐播放器(播放列表)、类库展示器(树形类结构)等
- 前言在RequestMappingHandlerAdapter对request进行了适配,并且调用了目标handler之后,其会返回一个Mo
- 前言在上一篇 Spring boot + LayIM + t-io 文件上传、 监听用户状态的实现 中,已经介绍了两个小细节:用户的在离线状
- 素数就是质数,就是只能被1整除,不能被其他数整除的数java程序为:public static void main(String[] arg
- import java.util.Calendar;import java.util.Date;public class Matrix {&
- 先讲一下java中的反射:反射就是将类别的各个组成部分进行剖析,可以得到每个组成部分,就可以对每一部分进行操作反射机制应用场景:逆向代码、动
- 我们知道,Spring可以通过包扫描将使用@Component注解定义的Bean定义到容器中。今天就来探究下他实现的原理。首先,找到@Com
- 1. pom.xml文件配置<?xml version="1.0" encoding="UTF-8&qu
- 概况Java的Long类主要的作用就是对基本类型long进行封装,提供了一些处理long类型的方法,比如long到String类型的转换方法
- 1.查询后获取对应的数据集后,传递参数strcodeName,根据数据集中strcodeName的匹配对应字段,获取数据集中对应的目的字段p
- 1.创建阻塞的服务器当 ServerSocketChannel 与 SockelChannel 采用默认的阻塞模式时,为了同时处理多个客户的
- 这篇山寨一个新版QQ的列表滑动删除,上篇有说到QQ的滑动删除,推测原理就是ListView本身每个item存在一个Button,只不过普通的
- 最近一个项目中,需要用到Java的websocket新特性,于是就学了一下,感觉这技术还挺好玩的,瞬间知道网页上面的那些在线客服是怎么做的了
- 本文以实例形式讲述了C#泛型的用法,有助于读者深入理解C#泛型的原理,具体分析如下:首先需要明白什么时候使用泛型:当针对不同的数据类型,采用
- 继承什么是继承呢?继承(Inheritance)是一种联结类与类的层次模型。指的是一个类(称为子类、子接口)继承另外的一个类(称为父类、父接
- 一、项目简述功能:用户的邮箱注册、验证码验证以及用户登录。 不需要注册账号,也可以上传满足条件的临时文件,但是只4小时内有效。 文件的管理,
- 本文实例讲述了java实现将结果集封装到List中的方法。分享给大家供大家参考,具体如下:import java.sql.Connectio
- 前言CompletableFuture实现了CompletionStage接口和Future接口,前者是对后者的一个扩展,增加了异步回调、流
- 在C#的数字运算过程中,有时候针对十进制decimal类型的计算需要保留2位有效小数,针对decimal变量保留2位有效小数有多种方法,可以