Spring boot实现文件上传功能

作者:卡通人物nnn 时间:2023-08-01 07:00:02 

本文实例为大家分享了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

标签:Spring,boot,文件上传
0
投稿

猜你喜欢

  • C语言由浅入深讲解文件的操作下篇

    2022-12-05 21:21:54
  • java实现给图片加铺满的网格式文字水印

    2023-07-30 05:22:12
  • 一文搞懂Java ScheduledExecutorService的使用

    2022-11-22 14:23:35
  • android 7自定义相机预览及拍照功能

    2023-01-29 06:56:34
  • Spring Boot和Kotlin的无缝整合与完美交融

    2022-07-08 04:54:09
  • Android自定义View仿探探卡片滑动效果

    2023-03-18 14:54:16
  • SpringBoot整合Mybatis自定义拦截器不起作用的处理方案

    2023-03-19 04:35:14
  • Android应用内悬浮窗的实现方案示例

    2022-05-07 20:29:24
  • android 更改TextView中任意位置字体大小和颜色的方法

    2021-10-21 01:51:43
  • Android开发之使用ViewPager实现图片左右滑动切换效果

    2022-11-12 11:44:59
  • Android自定义控件之继承ViewGroup创建新容器

    2023-06-15 08:50:11
  • android在异步任务中关闭Cursor的代码方法

    2022-04-21 18:07:32
  • Android实现APP秒表功能

    2022-11-13 13:58:26
  • Java_异常类(错误和异常,两者的区别介绍)

    2023-09-19 08:53:27
  • Java中Collection、List、Set、Map之间的关系总结

    2022-11-18 21:41:42
  • Winform下实现图片切换特效的方法

    2023-04-20 21:26:28
  • MyBatisPlus代码生成器的使用示例

    2022-04-28 07:52:42
  • Activity配置、启动和关闭activity实例详解

    2022-12-09 04:10:57
  • Java实现调用外部程序的示例代码

    2023-11-10 06:43:12
  • springboot过滤器和拦截器的实例代码

    2021-09-14 04:53:17
  • asp之家 软件编程 m.aspxhome.com