配置
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
/**
* 上传文件配置
* @author yuhao
*/
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 置文件大小限制 ,超出此大小页面会抛出异常信息//KB,MB
factory.setMaxFileSize("100MB");
// 设置总上传数据总大小
factory.setMaxRequestSize("100MB");
// 设置文件临时文件夹路径
// factory.setLocation("E://test//");
// 如果文件大于这个值,将以文件的形式存储,如果小于这个值文件将存储在内存中,默认为0
// factory.setMaxRequestSize(0);
return factory.createMultipartConfig();
}
}
controller
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@Api(tags = "文件上传", description = "FileController")
@RequestMapping(value = "/file")
@SuppressWarnings("all")
public class FileController {
// @Autowired
// private imgService service;
//获取主机端口
@Value("${server.port}")
private String port;
//获取本机ip
@Value("${server.host}")
private String host;
//图片存放根路径
private String rootPath = "C:";
//用户上传图片存放根目录下的子目录
private String sonPath = "/file/";
//日期目录
private String datePath;
//获取图片链接
private String imgPath;
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@PostMapping(value = "/upload")
@ApiOperation(value = "单文件上传")
public Result upload(@RequestParam("file") MultipartFile file) {
//返回上传的文件是否为空,即没有选择任何文件,或者所选文件没有内容。
//防止上传空文件导致奔溃
if (file.isEmpty()) {
return fail("文件为空");
}
//获取本机IP
// try {
// host = InetAddress.getLocalHost().getHostAddress();
// } catch (UnknownHostException e) {
// logger.error("get server host Exception e:", e);
// }
// 获取文件名
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if (Constants.SUFFIX_IMAGE.contains(suffixName.toLowerCase())) {
sonPath = "/file/imgs/";
}
if (Constants.SUFFIX_AUDIO.contains(suffixName.toLowerCase())) {
sonPath = "/file/audio/";
}
if (Constants.SUFFIX_VIDEO.contains(suffixName.toLowerCase())) {
sonPath = "/file/video/";
}
logger.info("上传的文件名为:" + fileName);
// 设置文件上传后的路径
// 解决中文问题,liunx下中文路径,图片显示问题
fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
+ "-" + UUIDUtil.getUUID() + suffixName;
datePath = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
String filePath = rootPath + sonPath + datePath;
logger.info("上传的文件路径" + filePath);
logger.info("整个图片路径:" + "http://" + host + ":" + port + sonPath + datePath + fileName);
//创建文件路径
File dest = new File(filePath + fileName);
imgPath = (host + ":" + port + sonPath + datePath + fileName).toString();
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
//假如文件不存在即重新创建新的文件已防止异常发生
dest.getParentFile().mkdirs();
}
try {
//transferTo(dest)方法将上传文件写到服务器上指定的文件
file.transferTo(dest);
//将链接保存到URL中
//imgTest imgTest = service.add(new imgTest(), imgPath);
return success((sonPath + datePath + fileName).toString());
} catch (Exception e) {
return fail("上传失败");
}
}
@PostMapping(value = "/uploadBatch")
@ApiOperation(value = "批量文件上传")
public Result uploadBatch(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
//List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
BufferedOutputStream stream = null;
List<String> result = new ArrayList<>();
for (MultipartFile file : files) {
if (!file.isEmpty()) {
// 获取文件名
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if (Constants.SUFFIX_IMAGE.contains(suffixName.toLowerCase())) {
sonPath = "/file/imgs/";
}
if (Constants.SUFFIX_AUDIO.contains(suffixName.toLowerCase())) {
sonPath = "/file/audio/";
}
if (Constants.SUFFIX_VIDEO.contains(suffixName.toLowerCase())) {
sonPath = "/file/video/";
}
logger.info("上传的文件名为:" + fileName);
// 设置文件上传后的路径
// 解决中文问题,liunx下中文路径,图片显示问题
fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
+ "-" + UUIDUtil.getUUID() + suffixName;
datePath = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
String filePath = rootPath + sonPath + datePath;
logger.info("上传的文件路径" + filePath);
logger.info("整个图片路径:" + host + ":" + port + sonPath + datePath + fileName);
//创建文件路径
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
//假如文件不存在即重新创建新的文件已防止异常发生
dest.getParentFile().mkdirs();
}
try {
// byte[] bytes = file.getBytes();
// stream = new BufferedOutputStream(new FileOutputStream(dest));
// stream.write(bytes);
// stream.close();
//transferTo(dest)方法将上传文件写到服务器上指定的文件
file.transferTo(dest);
result.add((sonPath + datePath + fileName).toString());
} catch (Exception e) {
stream = null;
return fail("You failed to upload " + " => " + e.getMessage());
}
} else {
return fail("You failed to upload " + " because the file was empty.");
}
}
return success(result);
}
//文件下载相关代码
@GetMapping("/download")
@ApiOperation(value = "文件下载")
public ResponseEntity downloadFile(HttpServletRequest request, HttpServletResponse response,
@ApiParam(value = "文件名", required = true) @RequestParam(name = "fileName", required = true) String fileName) {
//String fileName = "aim_test.txt";// 设置文件名,根据业务需要替换成要下载的文件名
if (fileName != null) {
//设置文件路径
String realPath = "C:\\imgs\\";
File file = new File(realPath, fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
/*int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}*/
int bytesRead = 0;
while ((bytesRead = bis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
System.out.println("success");
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}