头像上传和展示
1.环境:
springboot
2.前端
<form action="dept/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit">
</form>
<image src="http://localhost/upload/a.jpg"></image>
也可以使用vue+element
3.后端:
1.配置springmvc资源映射
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FilePathConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:D:/img/");
}
}
这里我选择D盘下的img文件夹,你们随意
测试:
1.在D盘放一张图片a.jpg
2.启动springboot项目访问http://localhost/upload/a.jpg
3.如果可以看到图片测试成功
2.开始上传图片
上传图片代码:
@PostMapping("/upload")
public String upload(@RequestParam("file")MultipartFile file){
try{
String originalFilename = file.getOriginalFilename();
File path = new File("D:/img");
if (!path.exists()){
path.mkdirs();
}
Assert.notNull(originalFilename,"没有上传文件");
String newName = String.valueOf(System.currentTimeMillis()).concat(originalFilename.substring(originalFilename.lastIndexOf(".")));
File file1 = new File(path.getAbsolutePath() + "/" + newName);
file.transferTo(file1);
return "/shopdemo/upload/".concat(newName);
}catch (Exception e){
return "上传失败!";
}
}
这里上传的图片后返回的是图片的路径
4.显示图片
<image src="上传返回的图片路径"></image>
标签:String,展示,upload,头像,file,path,上传,originalFilename
From: https://www.cnblogs.com/WangJingjun/p/16775877.html