Java 上传图片至阿里 OSS 文件存储系统,java 面试问题及答案
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
</dependency>
以上传文件夹为例,工作中正好遇到这个需求,简单记录一下。
前端界面
接口
ossUtils 工具类
cesh
/**
上传文件
dugt1998@163.com
*/
public String uploadImage(MultipartFile file) throws Exception {
InputStream in = file.getInputStream();
String fileOriginalFilename = file.getOriginalFilename();
String fileName = fileOriginalFilename.split("/")[1];
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(in.available());
metadata.setCacheControl("no-cache");
metadata.setHeader("Access-Control-Allow-Origin", "*");
metadata.setHeader("Access-Control-Allow-Methods", "POST GET HEAD PUT DELETE");
metadata.setHeader("Access-Control-Max-Age", "3600");
metadata.setHeader("Pragma", "no-cache");
metadata.setContentEncoding("utf-8");
metadata.setContentType(fileName);
OSS oss = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
oss.putObject(bucket, fileDir + fileName, in, metadata);
oss.shutdown();
in.close();
return "https://" + bucket + "." + endPoint + "/" + fileDir + fileName;
}
老样子,写完测试?
OK!!!
Oss utils
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.*;
/**
@author dugt1998@163.com
@date 2020/11/21 9:13
*/
@Component
public class OSSUtils {
private static final String END_POINT = "oss-cn-qingdao.aliyuncs.com";
private static final String ACCESS_KEY_ID = "";
private static final String ACCESS_KEY_SECRET = "";
private static final String BUCKET = "";
private static final String FILE_DIR = "test/";
/**
上传文件
dugt1998@163.com
*/
public String uploadImage(MultipartFile file) throws Exception {
InputStream in = file.getInputStream();
String fileName = file.getOriginalFilename();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(in.available());
metadata.setCacheControl("no-cache");
metadata.setHeader("Access-Control-Allow-Origin", "*");
metadata.setHeader("Access-Control-Allow-Methods", "POST GET HEAD PUT DELETE");
metadata.setHeader("Access-Control-Max-Age", "3600");
metadata.setHeader("Pragma", "no-cache");
metadata.setContentEncoding("utf-8");
metadata.setContentType(getContentType(fileName));
OSS oss = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
oss.putObject(BUCKET, FILE_DIR + fileName, in, metadata);
总结
对于面试,一定要有良好的心态,这位小伙伴面试美团的时候没有被前面阿里的面试影响到,发挥也很正常,也就能顺利拿下美团的 offer。小编还整理了大厂 java 程序员面试涉及到的绝大部分面试题及答案,希望能帮助到大家,
最后感谢大家的支持,希望小编整理的资料能够帮助到大家!也祝愿大家都能够升职加薪!
评论