Spring上传文件
工作中用的最多的就是上传,目前上传大概有三种形式:单文件
,多文件
,Base64
三种形态,spring
借助于commons-fileupload
来实现以上三种形态,是非常简单的一件事情。
添加依赖
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n6" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</pre>
Spring是通过
MultipartFile file
来接收文件,通过MultipartFile[] files
接收多个文件
实操
编写静态页面
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" cid="n18" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>上传Deme</h2>
<div>
<form method="POST" enctype="multipart/form-data" action="/uploads/upload1">
<p>
单文件上传:<input type="file" name="file"/>
<input type="submit" value="上传"/>
</p>
</form>
</div>
<h2>批量上传Demo</h2>
<div>
<form method="POST" enctype="multipart/form-data"
action="/uploads/upload2">
<p>
<input type="file" name="file"/>
</p>
<p>
文件2:<input type="file" name="file"/>
</p>
<p>
<input type="submit" value="上传"/>
</p>
</form>
</div>
<h2>Base64文件上传</h2>
<div>
<form method="POST" action="/uploads/upload3">
<p>
BASE64编码:<textarea name="base64" rows="10" cols="80"></textarea>
<input type="submit" value="上传"/>
</p>
</form>
</div>
</body>
</html></pre>
增加展示视图
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n29" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> public void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
registry.addViewController("/upload").setViewName("upload");
WebMvcConfigurer.super.addViewControllers(registry);
}</pre>
修改默认上传限制
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n35" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> @Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10000000);
return multipartResolver;
}</pre>
编写控制器
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n24" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">package com.haojishu.demo.web;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
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;
/**
- @ClassName: UploadController
- @Description:演示上传文件的各种操作
- @author: 心肝宝贝
- @date: 2019年5月25日 下午5:51:10
- @Copyright: 2019 www.haojishu.com Inc. All rights reserved.
- 注意:本内容仅限于公司内部传阅,禁止外泄以及用于其他的商业目
*/
@Controller
public class UploadController {
@Autowired
private HttpServletRequest request;
/**
- @Title: oneUpload
- @Description: 单文件上传演示
- @param: @param file
- @param: @return
- @param: @throws IllegalStateException
- @param: @throws IOException
- @return: String
- @throws
*/
@RequestMapping(value ="/upload/oneUpload",produces = "application/json;charset=utf-8")
@ResponseBody
public String oneUpload(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException{
if (file.isEmpty()) {
System.out.println("上传文件为空");
return "上传文件不能为空";
}else {
System.out.println("开始上传");
String path = request.getServletContext().getRealPath("/upload");
File isFile = new File(path);
if (!isFile.exists()) {
isFile.mkdirs();
}
file.transferTo(new File(path, new String(file.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8")));
return "上传成功" + path;
}
}
/**
- @Title: multipleUpload
- @Description: 多文件上传
- @param: @param files
- @param: @return
- @param: @throws IllegalStateException
- @param: @throws IOException
- @return: String
- @throws
*/
@RequestMapping(value ="/upload/multiple",produces = "application/json;charset=utf-8")
@ResponseBody
public String multipleUpload(@RequestParam("file") MultipartFile[] files) throws IllegalStateException, IOException{
if (files.length<1) {
System.out.println("上传文件为空");
return "上传失败";
}else {
System.out.println("开始上传");
String path = request.getServletContext().getRealPath("/upload");
File isFile = new File(path);
if (!isFile.exists()) {
isFile.mkdirs();
}
for (MultipartFile file : files) {
file.transferTo(new File(path, new String(file.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8")));
}
return "上传成功" + path;
}
}
@RequestMapping(value ="/upload/base64",produces = "application/json;charset=utf-8")
@ResponseBody
public String base64Upload(String base64) throws Exception {
String[] fileArray = base64.split("base64,");
final byte[] bytes = Base64Utils.decodeFromString(fileArray.length > 1 ? fileArray[1] : fileArray[0]);
String path = request.getServletContext().getRealPath("/upload");
File isFile = new File(path);
if (!isFile.exists()) {
isFile.mkdirs();
}
String suffix = "";
if("data:image/jpg;".equalsIgnoreCase(fileArray[0])){
suffix = ".jpg";
}else{
throw new Exception("上传图片格式不合法" + fileArray[0]);
}
File tempFile = new File(path + "/" + new Date().getTime() + suffix);
FileCopyUtils.copy(bytes, tempFile);
return "文件上传成功"+ path;
}
}</pre>