上传文件
1.导入jar包
<!-- 上传文件依赖的包--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
2.配置文件解析器(springboot可跳过)
注意:bean的id必须为:,否则上传文件会包400错误
3.编写页面(后端设计的可跳过)
4.编写控制器
在UserController.java中编写控制器
/** * 上传文件 * @param file * @return */ @PostMapping("upload") public R upload(MultipartFile file){ //可以获取到的文件信息 System.out.println("文件名:"+file.getOriginalFilename()); System.out.println("文件大小:"+file.getSize()); System.out.println("MIME类型:"+file.getContentType()); System.out.println("标签名:"+file.getName()); System.out.println("是否为空:"+file.isEmpty()); String fileName=file.getOriginalFilename(); //新文件名 String randowFileName= UUID.randomUUID().toString().replace("-",""); //获取 原始文件的后缀名 String extension= FilenameUtils.getExtension(fileName); //新文件名+后缀=新文件名称 String newFileName=randowFileName+"."+extension; //创建一个新文件 File newFile =new File(fileUploadUrl+newFileName); //传输文件信息 try { file.transferTo(newFile); return R.ok(200,"文件上传成功","/images/"+newFileName); } catch (IOException e) { throw new RuntimeException(e); //return R.error(200,"文件上传失败"); } }
5.在application.properties进行配置
#配置文件上传的保存路径 file.url.upload=E:/images/ #配置文件上传的虚拟目录(就是客户端访问路径) file.url.static=/images/**
6.在UserController添加注解注入
@Value("${file.url.upload}") private String fileUploadUrl;
7.新建config包,包含有WebConfig.java类
package com.example.shop.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * web的配置类 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Value("${file.url.upload}") private String fileUploadUrl; @Value("${file.url.static}") private String fileStaticUrl; @Override public void addResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler(fileStaticUrl).addResourceLocations("file:"+fileUploadUrl); } }