Spring 文件上传功能

简介:

本篇文章,我们要来做一个Spring的文件上传功能:

1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖:

1
2
3
4
5
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
     <version> 1.0 . 2 .RELEASE</version>
</dependency>

2.在webapp目录下的index.jsp文件中输入一个表单:

1
2
3
4
5
6
7
8
9
10
<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>
</html>

这个表单就是我们模拟的上传页面。

3. 编写处理这个表单的Controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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文件

1
2
3
4
5
6
7
8
9
10
<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文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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了,是不是很简单啊。

 

注意:上面的代码只是为了演示而已,所以编码风格上采取了随性的方式,不建议大家模仿。

 

参考资料:

1. MultipartResolver也可以实现文件上传功能。参考文章:http://mylfd.iteye.com/blog/1893648

目录
相关文章
|
10月前
|
人工智能 前端开发 数据可视化
2024年低代码趋势洞察——企业最看重的功能有哪些
随着数字化转型加速,低代码平台从“可选”变为企业技术战略的“必需品”。预计2024年全球超70%企业将引入低代码工具,以应对市场需求和技术挑战。低代码平台通过可视化开发、五大核心引擎(SQL、功能、模板、图表、切面引擎)、模型驱动开发、高效数据处理、AI智能助力及灵活插件生态,大幅简化开发流程,提升效率和质量,降低开发门槛,支持多行业复杂业务需求。其强大的技术架构和企业级特性,如微服务架构、开源支持、数据增删改查、图表创建等,进一步增强了企业的运营效率和决策能力。未来,低代码平台将更深度融合AI、数据分析和云原生架构,推动企业数字化创新。
227 21
|
人工智能
【AI Make Money】如何用人工智能赚钱
【AI Make Money】如何用人工智能赚钱
1957 0
|
存储 运维 监控
云原生技术架构成熟度模型解读| 学习笔记
快速学习云原生技术架构成熟度模型解读
云原生技术架构成熟度模型解读| 学习笔记
|
Web App开发 缓存 Cloud Native
Serverless 年终技术盘点 :工业、学术、社区遍地开花,国内厂商迅速卡位
预计 2021 年,将会有大量主流企业的核心应用,从原来的主机架构迁移到 Serverless 架构。
|
关系型数据库 PostgreSQL 索引
postgresql 物化视图
postgresql 物化视图的使用介绍
665 0
|
机器学习/深度学习 数据采集 存储
阿里云acp考试综述 阿里云acp考试真题分享
云计算云服务是当前国家支持建设的高新技术领域,同时也为从业者提供了良好的职业发展前途,是很多相关专业技术人员都梦寐以求的就业岗位。然而从事这一领域的工作需要较高的理论知识和实践能力,通过阿里云认证考取资格证是至关重要的一步。为了帮助更多的考生能顺利通过认证,现在就为大家介绍阿里云acp考试相关内容,并分享阿里云acp考试真题。
602 0
阿里云acp考试综述 阿里云acp考试真题分享
|
机器学习/深度学习 人工智能 分布式计算
PAI:一站式云原生AI平台
本文是《飞天大数据产品价值解读系列》之《一站式云原生AI平台》的视频分享精华总结,主要由阿里云机器学习PAI团队的产品经理高慧玲(花名:玲汐)向大家介绍了阿里巴巴整体的AI情况以及一站式云原生的AI平台PAI,并且做了简单的DEMO演示。
4821 0
PAI:一站式云原生AI平台
国际顶级域名后缀列表汇总大全
国际顶级域名包括COM、NET、GOV、EDU、ORG等常见的登记域名,国际顶级域名后缀列表大全:
|
数据库 Windows
windows激活报错0x80070020或0x80041010
windows激活报错0x80070020或0x80041010
windows激活报错0x80070020或0x80041010