一、1.1(关键)映射配置
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author zhangjiahao */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** * 资源映射路径 * addResourceHandler:访问映射路径 * addResourceLocations:资源绝对路径 */ registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/"); } }
1.2 有拦截器的话需要放行upload目录(InterceptorConfig是拦截器的类名,根据自己项目类自行修改)
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author zhangjiahao * @date 2020/1/10 16:04 */ @Configuration public class LoginConfig implements WebMvcConfigurer { @Bean public InterceptorConfig interceptorConfig(){ return new InterceptorConfig(); } @Override public void addInterceptors(InterceptorRegistry registry) { //注册TestInterceptor拦截器 InterceptorRegistration registration= registry.addInterceptor(new InterceptorConfig()); registration.addPathPatterns("/**"); //所有路径都被拦截 registration.excludePathPatterns( //添加不拦截路径 "/***", //登录 "/upload/**" //图片 ); } }
二、MultipartFile上传文件代码
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam(value = "file") MultipartFile file) throws IOException { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif"); if (!extList.contains(suffixName)) { return "图片格式非法"; } // 解决中文问题,liunx下中文路径,图片显示问题 fileName = UUID.randomUUID().toString().replace("-", "") + suffixName; // 返回客户端 文件地址 URL String url = "localhost:8080"+"/upload/" + fileName; File dest = new File( uploadDir + fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } file.transferTo(dest); return url; }
三、base64类型上传文件代码(根据自己的实际代码改动即可)
@RequestMapping(value = "/uploadBase64", method = RequestMethod.POST) public Object upload(@RequestParam String image) throws IOException { try { // image格式: "data:image/png;base64," + "图片的base64字符串" MultipartFile multipartFile = Base64Util.base64ToMultipart(image); String originalFilename = multipartFile.getOriginalFilename(); // 文件扩展名 String ext = originalFilename.substring(originalFilename.lastIndexOf(".")).trim(); List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif"); if (!extList.contains(ext)) { return new BaseResult(HttpStatus.INTERNAL_SERVER_ERROR,"图片格式非法"); } String randomFilename = UUID.randomUUID().toString().replace("-", "") + ext; //将文件写入服务器 String fileLocalPath = uploadDir + randomFilename; File localFile = new File(fileLocalPath); multipartFile.transferTo(localFile); InetAddress address = InetAddress.getLocalHost(); //写入服务器成功后组装返回的数据格式 return new BaseResult(HttpStatus.OK,address.getHostAddress()+":8080/upload/" + randomFilename); } catch (Exception e) { logger.error("上传图片失败:", e); } return new BaseResult(HttpStatus.INTERNAL_SERVER_ERROR); }
import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.IOException; /** * @author zhangjiahao */ @Slf4j public class Base64Util { public static MultipartFile base64ToMultipart(String base64) { try { String[] baseStr = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStr[1]); for(int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStr[0]); } catch (IOException e) { log.error(e.getMessage()); return null; } } }
import org.springframework.web.multipart.MultipartFile; import java.io.*; /** * 自定义的MultipartFile的实现类,主要用于base64上传文件,以下方法都可以根据实际项目自行实现 * * @author zhangjiahao */ public class BASE64DecodedMultipartFile implements MultipartFile { private final byte[] imgContent; private final String header; public BASE64DecodedMultipartFile(byte[] imgContent, String header) { this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() { return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() { return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @Override public boolean isEmpty() { return imgContent == null || imgContent.length == 0; } @Override public long getSize() { return imgContent.length; } @Override public byte[] getBytes() throws IOException { return imgContent; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { new FileOutputStream(dest).write(imgContent); } }
springboot上传图片到本地或者阿里云服务器,然后本地访问或者外网访问的步骤
原文:https://www.cnblogs.com/zhangjiahao/p/12204999.html