前言
意图使用Springboot开发完成文件上传下载服务,将其以docker容器形式部署至服务器。
文件上传
首先,在项目工程目录结构上,构建Controller层、Service层。
1、代码片段
Controller层:
/*
* 实现文件上传
*/
@Controller
@RequestMapping(value = "/upload")
@ResponseBody
@Slf4j
public class FileUploadController {
@Autowired
private FileUploadService fileUploadService;
@RequestMapping(value = "/fileUpload")
public String fileUpload(@RequestParam("fileName") MultipartFile file){
String result = fileUploadService.fileUpload(file);
return result;
}
}
Service层:
@Service
@Slf4j
public class FileUploadService {
public String fileUpload(MultipartFile file){
if(file.isEmpty()){
return "false";
}
String fileName = file.getOriginalFilename();
String path = "./upload";
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try (FileOutputStream out = new FileOutputStream (dest)){
out.write(file.getBytes());
} catch (Exception e) {
log.error("文件上传失败 :"+ e);
return "false";
}
}
}
Note: file.transferTo( ); 此方法是Spring自带文件保存方法,其封装了write(),若路径是绝对路径,则使用没有问题;否则,会出现文件路径找不到错误。[查找相关资料显示,与spring-boot -starter-parent版本有关]
2、关于上传文件大小:
Springboot默认支持上传文件2M,超过2M文件,此处采用自定义maxFileSize、maxRequestSize;
新建配置类,加上@Configuration文件进行说明。
然后在类里面加上
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize("10240KB"); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
文件下载
1、代码片段
Controller层:
@Controller
@RequestMapping("/fileDownload")
public String downLoad(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String filename = request.getParameter("fileName");
String filePath = "./download" ;
File file = new File(filePath + "/" + filename);
if(file.exists()){ //判断文件父目录是否存在
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));//文件类型是按照文件的扩展名显示的,点保存后,文件以filename的值命名;适用于中文名出现情况
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
log.error("文件下载错误:"+ e);
}
finally {
if(bis!=null){
try{
bis.close();
}catch(Exception e){
log.error("BufferedInputStream流关闭异常:"+ e);
}
}
if(fis!=null){
try{
fis.close();
}catch(Exception e){
log.error("FileInputStream流关闭异常:"+ e);
}
}
if(os!=null){
try{
os.close();
}catch(Exception e){
log.error("OutputStream流关闭异常:"+ e);
}
}
}
return null;
}
Postman测试
http://localhost:8080/upload/fileUpload