11.12 ali-oss上传图片
1.上传到服务器:
@PostMapping("/upload")
public String upload(MultipartFile file) {
if (file.isEmpty()) {
return "图片上传失败";
}
System.out.println();
String OriginalfileName = file.getOriginalFilename();
String ext=OriginalfileName.substring(OriginalfileName.lastIndexOf("."));
String uuid= UUID.randomUUID().toString().replace("-","");
String fileName = uuid + ext;
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+"\\src\\main\\resources\\images\\";
String path=pre+fileName;
// System.out.println(path);
try {
file.transferTo(new File(path));
} catch (IOException e) {
throw new RuntimeException(e);
}
return path;
}
如果项目部署在多台服务器上,这样的话如果用户上传时是服务器1,之后访问服务器2就访问不到之前的文件了。
2.上传到oss阿里云对象存储
UploadUtil.java
package com.haole.testdemo1.Utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class UploadUtil {
public static final String ALI_DOMAIN="https://(自己的domain名).oss-cn-beijing.aliyuncs.com/";
public String uploadImage(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
String ext="."+ FilenameUtils.getExtension(originalFileName);
String uuid= UUID.randomUUID().toString().replace("-","");
String fileName = uuid + ext;
//地域节点
String endpoint="http://oss-cn-beijing.aliyuncs.com";
String accessKeyId="自己的accessKeyId";
String accessKeySecret="自己的accessKeySecret";
OSS ossclient= new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
ossclient.putObject("vastjoyupload",fileName,file.getInputStream());
ossclient.shutdown();
return ALI_DOMAIN+fileName;
}
}
调用工具类实现上传接口
@PostMapping("/uploadImg")
public String upload2(MultipartFile file) throws IOException {
UploadUtil uploadUtil=new UploadUtil();
String result = uploadUtil.uploadImage(file);
return result;
}
标签:String,ali,oss,11.12,fileName,file,new,import
From: https://www.cnblogs.com/vastjoy/p/18542055