参考地址:How2J 的 Java教程How2J的Java教程, 内容涵盖J2SE、WEB前端、J2EE、框架技术等全面的Java内容。 基于实例代码和视频讲解的学习方式为Java职业生涯打下坚实的基础https://how2j.cn/p/9040
步骤:
1、用IDEA新建一个springboot项目,引入web starter
==============================================================
2、前端页面
需要引入vue和elementUI和axios,上官网下载即可。
文件上传
3、Controller层DemoUpladDownLoadImg.java
package com.ldj.reggie.controller.demoUpload;
import com.ldj.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
@RestController
@RequestMapping("/common")
@Slf4j
public class DemoUpladDownLoadImg {
@Value("${basePath}")
private String basePath;
@PostMapping("/upload")
public R upLoadImg(MultipartFile file) {
//debug到这。当前是存在C盘的一个临时文件
log.info(file.toString());
String originalFilename = file.getOriginalFilename();
//得到后缀名
int i = originalFilename.lastIndexOf(".");
String substring = originalFilename.substring(i);
//生成新文件名
String fileNewName = UUID.randomUUID().toString() + substring;
//转存到图片指定位置,位置在项目配置文件yml中指定
//判断存放图片的目录是否存在,不存在就创建
File dir = new File(basePath);
if (!dir.exists()) {
dir.mkdirs();
}
//存放在本机的文件名+后缀
File dest = new File(basePath + fileNewName);
try {
log.info("图片存放地址:" + basePath + fileNewName);
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
return R.success(fileNewName);
}
@GetMapping("/download")
public void downLoadImg(@RequestParam String name, HttpServletResponse response) {
log.info("想要的图片名字{}", name);
FileInputStream fileInputStream = null;
ServletOutputStream outputStream = null;
File file = new File(basePath + name);
try {
//输入流读取本机图片
fileInputStream = new FileInputStream(file);
response.setContentType("image/jpeg");
outputStream = response.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
assert outputStream != null;
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
4、在配置文件中指定保存路径
basePath: D:\
====================================
5、访问
http://localhost:8080/backend/page/demoUpload/upload.html
6、选择选择一张图片,成功上传到本机的D盘。
====================================================================
总结:
springboot的文件上传下载是基于Apache 基金会下面的一个子项目,子项目叫做commons,这个子项目中用于文件上传下载的包是commons-upload,然后commons-upload又基于commons-io。这些都集成在starter中了。
文件先是被临时存储在C盘,可以通过debug查看
后端必须使用file作为对象名:MultipartFile file,因为前端页面使用elementUI以表单方式上传图片的时候,自动给这个流取了个名叫file。当然也可以通过其他注解修改对象名。



