springboot项目base64上传图片

springboot项目base64上传图片

今天来分享一下自己的爬坑之路,图片上传分为MultipartFile上传和base64上传。今天只分享base64上传图片

配置路径

在application.properties文件中的配置如下

spring.servlet.multipart.maxFileSize=10Mb//最大上传文件
spring.servlet.multipart.maxRequestSize=10Mb//最小上传文件
file.uploadFolder=C:/file/  //上传的路径,此处因为本地测试服务器只有一个C盘
file.staticAccessPath=/file/  //回显路径

在文件中新建config包,在这个包下面新建WebConfiguration ,加注解**@Configuration**


package manage.config;

import java.io.File;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;



/**
 *
 * @author Administrator
 *
 */
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport{
     

	//读取配置文件配置
	@Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    
 // 跨域设置
  @Override
     public void addCorsMappings(CorsRegistry registry) {
     
         registry.addMapping("/**")
                 .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                 .allowedOrigins("*")
                 .maxAge(3600)
                 .allowCredentials(true)
                 .allowedHeaders("*");
         super.addCorsMappings(registry);
     }
  
  //配置图片回显
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
     
	  registry.addResourceHandler(staticAccessPath+"/**").addResourceLocations("file:" + uploadFolder+File.separator);
	// 解决静态资源无法访问
      registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
//      // 解决swagger无法访问
//      registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
//      // 解决swagger的js文件无法访问
//      registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
      registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
	  registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	  super.addResourceHandlers(registry);
  }
  @Override
  public void configureAsyncSupport(AsyncSupportConfigurer configurer){
     
      configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
      configurer.setDefaultTimeout(30000);
  }
}
package manage.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import manage.util.Base64Utils;
import manage.util.FileUtils;
import manage.util.Result;
import sun.misc.BASE64Decoder;

@SuppressWarnings({
      "unused" })
@RestController
@Api(value="文件上传controller",tags={
     "上传图片接口"})
public class FileUploadController {
     
	
	//读取配置文件(详见上面)
	@Value("${file.uploadFolder}")
    private String UPLOAD_FOLDER;

   /**
    * 
    * @Title: uploadImage
    * @Description:base64图片上传
    * @param base64Data
    * @return
    * @return Result
    * @author 薛锦涛
    * @date 2020年4月27日上午9:12:19
    */
   @ApiOperation("base64图片上传")
   @PostMapping("/base64Upload")
   public Result<Object> uploadImage(String base64Data){
     
       String dataPrix = ""; //base64格式前头
       String data = "";//实体部分数据
       if(base64Data==null||"".equals(base64Data)){
     
           return Result.error("上传失败,上传图片数据为空");
       }else {
     
           String [] d = base64Data.split("base64,");//将字符串分成数组
           if(d != null && d.length == 2){
     
               dataPrix = d[0];
               data = d[1];
           }else {
     
               return Result.error("上传失败,数据不合法");
           }
       }
       String suffix = "";//图片后缀,用以识别哪种格式数据
       //data:image/jpeg;base64,base64编码的jpeg图片数据
       if("data:image/jpg;".equalsIgnoreCase(dataPrix)){
     
           suffix = ".jpg";
       }else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){
     
           //data:image/x-icon;base64,base64编码的icon图片数据
           suffix = ".ico";
       } else if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){
     
           //data:image/x-icon;base64,base64编码的icon图片数据
           suffix = ".jpeg";
       }else if("data:image/gif;".equalsIgnoreCase(dataPrix)){
     
           //data:image/gif;base64,base64编码的gif图片数据
           suffix = ".gif";
       }else if("data:image/png;".equalsIgnoreCase(dataPrix)){
     
           //data:image/png;base64,base64编码的png图片数据
           suffix = ".png";
       }else {
     
           return Result.error("上传图片格式不合法");
       }
       String uuid = UUID.randomUUID().toString().replaceAll("-", "");
       String tempFileName=uuid+suffix;
       String imgFilePath = UPLOAD_FOLDER+tempFileName;//新生成的图片
       BASE64Decoder decoder = new BASE64Decoder();
       try {
     
    	   String replace = base64Data.replace(" ", "+");//这一句必须加,要不然写入图片会错误。
           String[] baseStrs = replace.split(",");
           byte[] b = new byte[0];
           b = decoder.decodeBuffer(baseStrs[1]);
           for (int i = 0; i < b.length; ++i) {
     
               if (b[i] < 0) {
     
                   b[i] += 256;
               }
           }
           OutputStream out = new FileOutputStream(imgFilePath);
           out.write(b);
           out.flush();
           out.close();
           String imgurl=UPLOAD_FOLDER+tempFileName;
           //imageService.save(imgurl);
           return Result.success(imgurl);
       } catch (IOException e) {
     
           e.printStackTrace();
           return Result.error("上传图片失败");
       }

   }
  


}


在使用 BASE64Decoder decoder = new BASE64Decoder(); 这个的时候,会报错无法导入包。
看这个 解决Eclipse无法使用BASE64Decoder decoder

第一次分享,如果有错误,欢迎大家指导改正

你可能感兴趣的:(springboot,java)