正文
代码结构如下
代码
pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xiaojie</groupId> <artifactId>pic-demo</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.2</version> <relativePath/> </parent> <!--七牛云--> <dependencies> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.qiniu</groupId> <artifactId>happy-dns-java</artifactId> <version>0.1.6</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>7.8.0</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
工具类
package com.xiaojie.upload.utils; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import org.springframework.stereotype.Component; /** * @Description:七牛云上传文件工具类 * @author: xiaojie * @date: 2021.07.27 */ @Component public class QiNiuUtils { private static final String ACCESS_KEY = "ACCESS_KEY"; private static final String SECRET_KEY = "SECRET_KEY"; //图片命名空间 private static final String BUCKET = "BUCKET"; //密钥配置 static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); //第二种方式: 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。 static Zone z = Zone.autoZone(); static Configuration c = new Configuration(z); //创建上传对象 static UploadManager uploadManager = new UploadManager(c); //简单上传,使用默认策略,只需要设置上传的空间名就可以了 public static String getUpToken() { return auth.uploadToken(BUCKET); } /* * * @param filePath 上传文件路径 * @param filename 上传到七牛云之后的路径 * @todo * @author xiaojie * @date 2021/7/28 9:59 * @return java.lang.String */ public static Response upLoadImage(String filePath, String filename) { Response res=null; try { //调用put方法上传 res = uploadManager.put(filePath, filename, getUpToken()); //打印返回的信息 System.out.println(res.bodyString()); } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 System.out.println(r.toString()); try { //响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException e1) { //ignore } } return res; } public static void main(String[] args) throws QiniuException { Response response1 = upLoadImage("C:\\Users\\HTGY02\\Desktop\\1.jpg", "00123.jpg"); System.out.println(response1.bodyString()); //qww9cg61f.hb-bkt.clouddn.com/1.jpg_ws.girl } }
生成文件名称工具类
枚举
package com.xiaojie.upload.myenum; public enum FileType { /** * JPEG */ JPEG("FFD8FF", "jpg"), /** * PNG */ PNG("89504E47", "png"), /** * GIF */ GIF("47494638", "gif"), /** * TIFF */ TIFF("49492A00"), /** * Windows bitmap */ BMP("424D"), /** * CAD */ DWG("41433130"), /** * Adobe photoshop */ PSD("38425053"), /** * Rich Text Format */ RTF("7B5C727466"), /** * XML */ XML("3C3F786D6C"), /** * HTML */ HTML("68746D6C3E"), /** * Outlook Express */ DBX("CFAD12FEC5FD746F "), /** * Outlook */ PST("2142444E"), /** * doc;xls;dot;ppt;xla;ppa;pps;pot;msi;sdw;db */ OLE2("0xD0CF11E0A1B11AE1"), /** * Microsoft Word/Excel */ XLS_DOC("D0CF11E0"), /** * Microsoft Access */ MDB("5374616E64617264204A"), /** * Word Perfect */ WPB("FF575043"), /** * Postscript */ EPS_PS("252150532D41646F6265"), /** * Adobe Acrobat */ PDF("255044462D312E"), /** * Windows Password */ PWL("E3828596"), /** * ZIP Archive */ ZIP("504B0304"), /** * ARAR Archive */ RAR("52617221"), /** * WAVE */ WAV("57415645"), /** * AVI */ AVI("41564920"), /** * Real Audio */ RAM("2E7261FD"), /** * Real Media */ RM("2E524D46"), /** * Quicktime */ MOV("6D6F6F76"), /** * Windows Media */ ASF("3026B2758E66CF11"), /** * MIDI */ MID("4D546864"); private String value = ""; private String ext = ""; FileType(String value) { this.value = value; } FileType(String value, String ext) { this(value); this.ext = ext; } public String getExt() { return ext; } public String getValue() { return value; } }
service
package com.xiaojie.upload.service.impl; import com.qiniu.http.Response; import com.qiniu.util.Json; import com.xiaojie.upload.myenum.FileType; import com.xiaojie.upload.service.UploadService; import com.xiaojie.upload.utils.QiNiuUtils; import com.xiaojie.upload.utils.StringUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * @Description: 上传图片的接口 * @author: xiaojie * @date: 2021.07.27 */ @Service @Slf4j public class UploadServiceImpl implements UploadService { //图片访问的域名 private final String IMAGE_URL = "http://qww9cg61f.hb-bkt.clouddn.com/"; //样式分隔符 private final String IMAGE_PART = "_"; //图片处理样式名称 private final String IMAGE_PATTERN = "ws.girl"; @Override public Map<String, Object> upload(MultipartFile uploadFile) throws Exception { Map resultMap = new HashMap(); if (uploadFile.isEmpty()) { throw new RuntimeException("the file is empty"); } FileType fileType = getFileType(uploadFile.getInputStream()); if (fileType == null) { throw new RuntimeException("fileType is null"); } String orgName = uploadFile.getOriginalFilename(); // 获取文件原始名称 //在linux环境部署时,请记得修改这个路径,目前没找到更好的办法 File temp = new File("D:\\temp"); //uploadFile是MultipartFile对象 uploadFile.transferTo(temp); //获取到文件绝对路径 String suffixName = orgName.substring(orgName.lastIndexOf(".")); //获取文件后缀 log.info("suffixName.................{}", suffixName); String newName = StringUtils.getString(15) + suffixName; // 文件名称 //七牛上传 Response response = QiNiuUtils.upLoadImage(temp.getPath(), newName); log.info("response.................{}", response.bodyString()); //获取上传后文件的key,文件名称 if (response == null) { throw new RuntimeException("qiniu response is null"); } resultMap = Json.decode(response.bodyString(), Map.class); String name = (String) resultMap.get("key"); //由于七牛云原图保护需要如下方式访问 域名+key(文件名)+_(样式分隔符)+ws.girl(图片处理样式名称) // qww9cg61f.hb-bkt.clouddn.com/1.jpg_ws.girl resultMap.clear(); resultMap.put("code", 200); resultMap.put("url", IMAGE_URL + name + IMAGE_PART + IMAGE_PATTERN); //删除临时文件 temp.delete(); return resultMap; } /* * 获取文件类型,校验文件格式是否正确 * @todo * @author xiaojie * @date 2021/7/28 11:05 * @return com.xiaojie.upload.myenum.FileType */ public static FileType getFileType(InputStream is) throws IOException { byte[] src = new byte[28]; is.read(src, 0, 28); StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v).toUpperCase(); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } FileType[] fileTypes = FileType.values(); for (FileType fileType : fileTypes) { if (stringBuilder.toString().startsWith(fileType.getValue())) { return fileType; } } return null; } }
Controller
package com.xiaojie.upload.api; import com.xiaojie.upload.service.UploadService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.Map; /** * @Description: * @author: xiaojie * @date: 2021.07.27 */ @RestController @Slf4j public class FileUpload { @Autowired private UploadService uploadService; @PostMapping("/upload") public Map<String, Object> upload(MultipartFile file) throws Exception { log.info("进入接口。。。。。。。。。。。。。。。"); Map<String, Object> result = uploadService.upload(file); log.info("file.................."+file); return result; } }
application.yml
spring: servlet: multipart: enabled: true max-file-size: 5MB max-request-size: 20MB