目录
基本概念
这个是基因Github的一个项目改的,因为页面关闭了,在此找不到了,不能把连接发上来。
这里使用的是FreeMarker。
为了避免重名,使用了UUID生成随机。
找图片文件主要是使用ResourceLoader。
代码与实例
程序运行截图如下:
点击选择文件,然后提交:
看看文件夹:
关键源码如下:
application.properties
### FreeMarker 配置
spring.freemarker.allow-request-override=false
#Enable template caching.启用模板缓存。
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#设置面板后缀
spring.freemarker.suffix=.ftl
# 设置单个文件最大内存
multipart.maxFileSize=50Mb
# 设置所有文件最大内存
multipart.maxRequestSize=50Mb
# 自定义文件上传路径
web.upload-path=F:/SpringTest/
TestController.java
package com.example.demo.controller;
import com.example.demo.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
@Controller
public class TestController {
private final ResourceLoader resourceLoader;
public TestController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Value("${web.upload-path}")
private String path;
@RequestMapping("test")
private String toUpload(){
return "test";
}
//上传文件
@RequestMapping("fileUpload")
public String upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map){
String localPath = "F:/SpringTest";
String msg = "";
StringBuffer newName = new StringBuffer();
if(FileUtils.upload(file, localPath, file.getOriginalFilename(), newName)){
msg = "上传成功";
}
else{
msg = "上传失败";
}
newName.toString();
map.put("msg", msg);
//map.put("fileName", file.getOriginalFilename());
map.put("fileName", newName.toString());
return "forward:/test";
}
//显示单张图片
@RequestMapping("show")
public ResponseEntity showPhotos(String fileName){
if(fileName == null){
return ResponseEntity.notFound().build();
}
try{
return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
}
catch (Exception e){
return ResponseEntity.notFound().build();
}
}
}
源码打包下载
地址如下: