springboot上传图片的经历
一开始,感觉一个简单的上传图片功能,应该也不会有什么难的!
百度一段代码,直接上!
1.首先贴一下上传文件的工具类
import java.io.File;
import java.io.FileOutputStream;
/**
* 文件工具类
*/
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}
2.再贴一下Controller层的代码
@Resource
HttpServletRequest request;
//处理文件上传
@RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
//设置文件上传路径
String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
return "上传成功";
} catch (Exception e) {
return "上传失败";
}
}
不得不说,用这个简单的代码是可以将图片上传成功的!但是,奇怪的是,代码保存的地方我是第一次碰见!
上传图片都跑到了C:\Users\ASUS\AppData\Local\Temp\tomcat-docbase.8011.12868084175756629730\uploaded\16311085334132.jpg
而且据说,这里的图片只要一旦重启tomcat,图片就都没有了!
不得已,又百度一篇
springboot上传图片文件
步骤一:基于前面springboot入门小demo
基于的springboot入门小demo,已包含了前面文章的知识点(比如:热部署、全局异常处理器)。
步骤二:创建uploadPage.jsp上传页面
在jsp目录下新建uploadPage.jsp,需要几点:
1. method="post" 是必须的
2. enctype="multipart/form-data" 是必须的,表示提交二进制文件
3. name="file" 是必须的,和后续服务端对应
4. accept="image/*" 表示只选择图片
步骤三:创建UploadController.java
因为uploadPage.jsp在WEB-INF下,不能直接从浏览器访问,所以要在这里加一个uploadPage跳转,这样就可以通过。
测试访问页面:http://127.0.0.1:8080/uploadPage
访问到uploadPage.jsp页面了(只是可以访问,还不能上传)。
@Controller
public class UploadController {
// 因为uploadPage.jsp 在WEB-INF下,不能直接从浏览器访问,所以要在这里加一个uploadPage跳转,这样就可以通过
@RequestMapping("/uploadPage")
public String uploadPage() {
return "uploadPage"; //过度跳转页
}
@PostMapping("/upload") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uplaod(HttpServletRequest req, @RequestParam("file") MultipartFile file, Model m) {//1. 接受上传的文件 @RequestParam("file") MultipartFile file
try {
//2.根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
String fileName = System.currentTimeMillis() + file.getOriginalFilename();
//3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名
String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;
//4.第一次运行的时候,这个文件所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
File destFile = new File(destFileName);
destFile.getParentFile().mkdirs();
//5.把浏览器上传的文件复制到希望的位置
file.transferTo(destFile);
//6.把文件名放在model里,以便后续显示用
m.addAttribute("fileName", fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
return "showImg";
}
}
步骤四:创建showImg.jps
文件最终上传到webapp下面的uploaded文件夹下面,如果看不到,就刷新一哈。
步骤五:修改application.properties
设置上传文件的大小,默认是1m,太小了,文件稍微大一点就会出错
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb
步骤六:测试
访问测试地址:http://127.0.0.1:8080/uploadPage
SpringBoot上传图片到服务器
一、自定义映射路径
@Configuration
public class ImgHandlerConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//文件磁盘图片url 映射
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
registry.addResourceHandler("/imgs/**").addResourceLocations("classpath:/imgs/");
}
}
二、上传接口
将图片放到类路径下的imgs文件夹中。没有该文件夹则自动创建出来。
@Controller
@RequestMapping("upload")
public class UploadController {
/**
*上传图片接口
*/
@PostMapping("uploadImg")
@ResponseBody
public String uploadFile(@RequestParam("fileName") MultipartFile file, HttpServletRequest request) throws FileNotFoundException {
//判断文件是否为空
if (file.isEmpty()) {
return "上传文件不可为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +fileName;
//放到类路径下的imgs文件夹中
String classpath = ResourceUtils.getFile("classpath:").getAbsolutePath();
String relativePath="/imgs/"+fileName;
String path=classpath+relativePath;
//创建文件路径
File dest = new File(path);
//判断文件是否已经存在
if (dest.exists()) {
return "文件已经存在";
}
//判断文件父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
//上传文件//保存文件
file.transferTo(dest);
} catch (Exception e) {
return "上传失败";
}
//服务器路径
String serverUrl=request.getRequestURL().toString().replace(request.getRequestURI(),"");
return serverUrl+relativePath;
}
}
上传图片之后直接访问接口返回路径即可。
springboot默认上传文件最大为1MB。可修改yml配置文件:
spring:
servlet:
multipart:
max-file-size: 20MB
max-request-size: 20MB
感谢
https://blog.csdn.net/weixin_43424932/article/details/104040917
https://blog.csdn.net/qq1271396448/article/details/86163901
https://www.cnblogs.com/zs-notes/p/9372618.html
有好的文章希望朋友们帮助分享推广,猛戳这里河洛伊哥