java实现阿里云上传图片,并解决上传图片文件的强制性下载
程序员文章站
2022-07-10 18:06:40
...
实现步骤:
1、导入依赖
2、配置文件(application.properties)
3、配置OssConfig
4、书写Service(interface)
2、书写Service(实现类)
3、书写Controller
1、导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
2、配置文件(application.properties)
# 阿里云云存储 OSS
oss.endpoint=oss-cn-shenzhen.aliyuncs.com
oss.domain=https://demo-project.com/
oss.bucket=demo-project
oss.accessId=***IQ3**rz***fx**
oss.accessKey=***y28hrO***B9eB0******
oss.default.dir=static/upload/
3、配置OssConfig
package com.mine.luotj.config.oss;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import lombok.Data;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author: create by luotj
* date: 2020-03-30 14:10
**/
@Data
@Component
@ConditionalOnProperty({"oss.endpoint", "oss.domain", "oss.bucket", "oss.accessId", "oss.accessKey", "oss.default.dir"})
public class OssConfig{
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.domain}")
private String domain;
@Value("${oss.bucket}")
private String bucket;
@Value("${oss.accessId}")
private String accessId;
@Value("${oss.accessKey}")
private String accessKey;
@Value("${oss.default.dir}")
private String dir;
@Bean
public CredentialsProvider provideCredentialsProvider() {
if (!Strings.isBlank(this.accessId) && !Strings.isBlank(this.accessKey)) {
return new DefaultCredentialProvider(this.accessId, this.accessKey);
} else {
throw new IllegalArgumentException("oss.accessId 或 oss.accessKey properties 不能为空");
}
}
@Bean
public ClientConfiguration provideClientConfiguration() {
return new ClientConfiguration();
}
@Bean(
destroyMethod = "shutdown"
)
public OSSClient provideOSSClient(@Autowired CredentialsProvider credentialsProvider, @Autowired ClientConfiguration clientConfiguration) {
return new OSSClient(this.endpoint, credentialsProvider, clientConfiguration);
}
}
4、书写Service(interface)
package com.mine.luotj.Service.oss;
import org.springframework.web.multipart.MultipartFile;
/**
* @author: create by luotj
* date: 2020-03-30 12:43
**/
public interface OssService {
String uploadPicture(MultipartFile multipartFile);
}
5、书写Service(实现类)
package com.mine.luotj.Service.oss;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.mine.luotj.config.oss.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author: create by luotj
* date: 2020-03-30 12:43
**/
@Slf4j
@Service
public class OssServiceImpl implements OssService {
@Autowired
private OssConfig ossConfig;
@Autowired
private OSSClient mOssClient;
@Override
public String uploadPicture(MultipartFile multipartFile) {
try {
/* 文件名 */
String fileName = multipartFile.getOriginalFilename();
/* 后缀名 */
String prefix = fileName.substring(fileName.lastIndexOf("."));
/* 获取文件流 */
InputStream inputStream = multipartFile.getInputStream();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + prefix;
//此处设置Content-type = image/jpg(解决上传图片访问链接强制性下载的情况,不设置则访问的路径打开效果是下载)
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
String objectName = sdf.format(new Date()) + "/" + finalFileName;
mOssClient.putObject(ossConfig.getBucket(), ossConfig.getDir() + objectName, inputStream, objectMetadata);
String accessUrl = ossConfig.getDomain().endsWith("/")
? ossConfig.getDomain() + ossConfig.getDir() + objectName
: ossConfig.getDomain() + ossConfig.getDir() + "/" + objectName;
return accessUrl;
} catch (Exception ex) {
log.error("msg:{}", ex.getMessage());
}
return null;
}
}
6、书写Controller
package com.mine.luotj.ui.controller.api.oss;
import com.mine.luotj.Service.oss.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 阿里云上传
*
* @author: create by luotj
* date: 2020-03-30 12:27
**/
@Api(tags = "05. 阿里云上传")
@RestController
@RequestMapping("/api/oss")
public class OssController {
@Autowired
private OssService ossService;
@ApiOperation("图片上传(返回路径)")
@PostMapping("/upload")
public String uploadPicture(@RequestPart(value = "file") MultipartFile multipartFile) {
return ossService.uploadPicture(multipartFile);
}
}
上传效果:
java解决文件oss上传强制性下载友情链接:
https://blog.csdn.net/oRanXiaoLuo/article/details/103364928
https://segmentfault.com/q/1010000015459762?sort=created