前言
文件上传
是web应用中,常见的操作之一。在Spring Boot中,我们可以很容易的完成这个功能。
具体编码
本节主要是基于MVC结构来讲述的,所以我们需要引入视图层的相关框架。
添加依赖
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
准备
-
在application.yml中添加上传相关配置
upload: path: ./upload/
-
新建upload文件夹,用于存放上传文件
编码
UploadController.java
package com.boot.demo.controller;
import com.boot.demo.service.UploadService;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/upload")
public class UploadController {
@Autowired
private UploadService uploadService;
@RequestMapping("index")
public ModelAndView index(){
ModelAndView mv = new ModelAndView();
mv.setViewName("/upload/index");
return mv;
}
@RequestMapping("uploadFile")
@ResponseBody
public Map uploadFile(@RequestParam(name = "file") MultipartFile[] file){
Map<String,String> result = new HashMap<>();
try {
uploadService.uploadFile(file);
result.put("code","200");
result.put("msg","上传成功");
} catch (Exception e){
result.put("code","500");
result.put("msg","上传失败");
}
return result;
}
@RequestMapping("uploadBase64File")
@ResponseBody
public Map uploadFile(@RequestParam String baseStr){
Map<String,String> result = new HashMap<>();
try {
uploadService.uploadBase64File(baseStr);
result.put("code","200");
result.put("msg","上传成功");
} catch (Exception e){
result.put("code","500");
result.put("msg","上传失败");
}
return result;
}
}
UploadService.java
package com.boot.demo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@Service
public class UploadService {
private static final Logger logger = LoggerFactory.getLogger(UploadService.class);
@Value("${upload.path}")
private String uploadPath;
public void uploadFile(MultipartFile...files){
for(MultipartFile file : files){
try {
uploadFile(file.getInputStream(), file.getOriginalFilename());
} catch (IOException e){
logger.error("上传失败...",e.getMessage(),e);
throw new RuntimeException();
}
}
}
public void uploadBase64File(String baseStr){
String[] strs = baseStr.split("base64,");
byte[] buf = Base64Utils.decodeFromString(strs.length > 1 ? strs[1] : strs[0]);
ByteArrayInputStream bis = new ByteArrayInputStream(buf);
try {
uploadFile(bis, "temp.png");
} catch (IOException e){
logger.error("上传失败...",e.getMessage(),e);
throw new RuntimeException();
}
}
private void uploadFile(InputStream inputStream,String name) throws IOException{
FileOutputStream fos = null;
try {
fos = new FileOutputStream(uploadPath + name);
} catch (FileNotFoundException ex) {
File file = new File(uploadPath + name);
file.createNewFile();
fos = new FileOutputStream(file);
}
try {
FileCopyUtils.copy(inputStream,fos);
} finally {
inputStream.close();
fos.flush();
fos.close();
}
}
}
BootApplication.java
package com.boot.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 上传文件
* Author : Ivan
**/
@SpringBootApplication
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class,args);
}
}
测试
接着,就可以自行启动项目,访问http://localhost:8080/upload/index进行单文件,多文件,Base64文件上传的测试了。
Base64测试
Base64文件,读者们可以访问Base64转换工具,将文件上传至该网站后,再将生成的字符串粘贴过来,就可以测试了。