FileUpLoadController
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @CrossOrigin @Api(value = "图片上传", tags = {"图片上传本地接口"}) @RequestMapping("/app/Upload") @RestController public class FileUpLoadController { private static Object URL = null; /** * Dong * @param file * @param request * @return */ @ApiOperation("图片上传") @PostMapping("/image") public AjaxResult uploadImg(MultipartFile file, HttpServletRequest request) { if (file.isEmpty()) { System.out.println("上传的文件为空!"); } // 文件名 String fileName =file.getOriginalFilename(); // 获取文件后缀名 String extension = fileName.substring(fileName.indexOf(".")); // 上传文件的路径,如果没有将自动创建 String uploadFolder = "D://upload/files/"; // 生成一个新的文件名 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String format = simpleDateFormat.format(new Date()); fileName = format+UUID.randomUUID() + extension; File dest = new File(uploadFolder + fileName); // 检测文件目录是否存在 不存在则创建 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); System.out.println("上传文件成功!"); } catch (IOException e) { e.printStackTrace(); System.out.println("上传文件失败!"); } URL="http://"+request.getServerName() + ":" + request.getServerPort()+"/upload/" + fileName; // 返回虚拟文件访问路径 return AjaxResult.success("image",URL); } }
UploadConfig
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @Author Dong * @Date * @Version 1.0 * 设置虚拟路径,访问绝对路径下资源 **/ @Configuration public class UploadConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/upload/**").addResourceLocations("file:D://upload/files/"); } }