欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Springboot2整合阿里云OSS实现文件上传、下载、删除、查看

程序员文章站 2022-06-28 18:45:50
1.阿里云配置2.pom文件 org.springframework.boot spring-boot-starter-web

1.阿里云配置

2.pom文件

          <!--<version>2.1.5.RELEASE</version> springboot版本-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>

3.配置文件

server.port=8083

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB

#地域节点
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
#用户accesskey id
aliyun.oss.file.keyid=xxxxxxxxxx
#用户accesskey secret
aliyun.oss.file.keysecret=xxxxxxxxxx
#相当于是哪个库
aliyun.oss.file.bucketname=xiaozhuya
#文件路径
aliyun.oss.file.filehost=avatar

4.配置类

public class ConstantPropertiesUtil implements InitializingBean {

	@Value("${aliyun.oss.file.endpoint}")
	private String endpoint;

	@Value("${aliyun.oss.file.keyid}")
	private String keyId;

	@Value("${aliyun.oss.file.keysecret}")
	private String keySecret;

	@Value("${aliyun.oss.file.filehost}")
	private String fileHost;

	@Value("${aliyun.oss.file.bucketname}")
	private String bucketName;

	public static String END_POINT;
	public static String ACCESS_KEY_ID;
	public static String ACCESS_KEY_SECRET;
	public static String BUCKET_NAME;
	public static String FILE_HOST ;

	@Override
	public void afterPropertiesSet() throws Exception {
		END_POINT = endpoint;
		ACCESS_KEY_ID = keyId;
		ACCESS_KEY_SECRET = keySecret;
		BUCKET_NAME = bucketName;
		FILE_HOST = fileHost;
	}

}

5.编写Service

public interface FileService {

	/**
	 * 文件上传至阿里云
	 * @param file
	 * @return
	 */
	String upload(MultipartFile file);

	void download(String name);

	void logDownload(String name, HttpServletResponse response) throws Exception;

	String deleteFile(String filename);
}

6.实现类

@Service
public class FileServiceImpl implements FileService {

    static String[] TYPESTR = {".png",".jpg",".gif",".jpeg"};

    @Override
    public String upload(MultipartFile file) {

        Boolean flag = false;
        for(String type : TYPESTR){
            if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)){
                flag = true;
                break;
            }
        }
        if(!flag){
           /* throw  new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);*/
            return  "文件格式不正确";
        }
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String uploadUrl="";
        try {
            //2、怎么判断文件内容—> 如果我上传的是rm -rf /* 脚本
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image == null){
             // throw  new GuliException(ResultCodeEnum.FILE_NULL_ERROR);
                return "文件内容不正确";
            } else{
                System.err.println(image.getHeight());
                System.err.println(image.getWidth());
            }
            //判断oss实例是否存在:如果不存在则创建,如果存在则获取
            OSSClient ossClient = new OSSClient(ConstantPropertiesUtil.END_POINT,
                    ConstantPropertiesUtil.ACCESS_KEY_ID,ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限:公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            //构建日期路径:avatar/2019/02/26/文件名
            String filePath = new DateTime().toString("yyyy/MM/dd");

            //文件名:uuid.扩展名
            String original = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString();
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;
            String fileUrl = ConstantPropertiesUtil.FILE_HOST + "/" + filePath + "/" + newName;

            //文件上传至阿里云
            ossClient.putObject(bucketName, fileUrl, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //获取url地址
            uploadUrl = "http://" + bucketName + "." + ConstantPropertiesUtil.END_POINT + "/" + fileUrl;

        } catch (IOException e) {
           // throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        return uploadUrl;
    }

    @Override
    public void download(String name) {
        OSSClient ossClient = new OSSClient(ConstantPropertiesUtil.END_POINT,
                ConstantPropertiesUtil.ACCESS_KEY_ID,ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        //构建日期路径:avatar/2019/02/26/文件名
        String filePath = new DateTime().toString("yyyy/MM/dd");
        File file = new File("E:\\imags.jpg");
        ossClient.getObject(new GetObjectRequest(ConstantPropertiesUtil.BUCKET_NAME, ConstantPropertiesUtil.FILE_HOST+"/" + filePath + "/"+name),file );
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public void logDownload(String name, HttpServletResponse response) throws Exception {
        OSSClient ossClient = new OSSClient(ConstantPropertiesUtil.END_POINT,
                ConstantPropertiesUtil.ACCESS_KEY_ID,ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        //设置响应头为下载
        response.setContentType("application/x-download");
        //设置下载的文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);
        response.setCharacterEncoding("UTF-8");
        String filePath = new DateTime().toString("yyyy/MM/dd");//上传的路径按理来说需要保持到数据库,显示连接到页面。
        String osskey = osskey(ConstantPropertiesUtil.FILE_HOST, filePath, name);
        OSSObject ossObject = ossClient.getObject(ConstantPropertiesUtil.BUCKET_NAME,osskey);
        InputStream is = ossObject.getObjectContent();
        BufferedInputStream bis = null;//定义缓冲流
        try {
            bis = new BufferedInputStream(is);//把流放入缓存流
            OutputStream os = response.getOutputStream();//定义输出流的响应流。
            byte[] buffer = new byte[1024];//定义一个字节数
            int len;//记录每次读入到cbuf数组中的字符的个数
            while ((len = is.read(buffer)) != -1) {//开始输出
                System.out.println(len);
                System.out.println(buffer);
                os.write(buffer,0,len); //从数组中每次写出len个字符
            }
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ossClient!=null){
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }

    @Override
    public String deleteFile(String filename) {
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = ConstantPropertiesUtil.FILE_HOST;
        String filePath = new DateTime().toString("yyyy/MM/dd");

      //建议在方法中创建OSSClient 而不是使用@Bean注入,不然容易出现Connection pool shut down
        OSSClient ossClient = new OSSClient(ConstantPropertiesUtil.END_POINT,
                ConstantPropertiesUtil.ACCESS_KEY_ID,ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        //删除目录中的文件,如果是最后一个文件fileoath目录会被删除。
        ossClient.deleteObject(bucketName,fileHost+"/" + filePath + "/"+filename);
        try {
        } finally {
            ossClient.shutdown();
        }
        return  "success";
    }
    public  String osskey(String fileHost,String filePath,String name){

        String osskey = fileHost+"/"+filePath+"/"+name;
        return  osskey;
    }
}

7.为了好测试加入Swagger

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

8.配置Swagger

@Configuration
@EnableSwagger2
public class Swagger2Config {

	@Bean
	public Docket webApiConfig(){

		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("webApi")
				.apiInfo(webApiInfo())
				.select()
				//.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
				.paths(Predicates.not(PathSelectors.regex("/error.*")))
				.build();

	}
	private ApiInfo webApiInfo(){
		return new ApiInfoBuilder()
				.title("网站-用户中心API文档")
				.description("本文档描述了课程中心微服务接口定义")
				.version("1.0")
				.contact(new Contact("Helen", "http://xxxxx.com", "xxxx@qq.com"))
				.build();
	}

}

9.控制层

@Api(description = "阿里云文件上传")
@RequestMapping("/oss/file")
@RestController
public class FileController {

    @Autowired
    FileService fileService;

    @ApiOperation(value = "文件上传阿里云")
    @PostMapping("upload")
    public R upload(MultipartFile file, @RequestParam(value="host", required = false) String host){
        if (file!=null){
            if(!StringUtils.isEmpty(host)){
                ConstantPropertiesUtil.FILE_HOST = host;
            }
            String uploadurl = fileService.upload(file);
            return  R.ok().data("url",uploadurl);
        }
        return  R.error().message("文件不能为空!");
    }
    @ApiOperation(value = "文件下载到本地")
    @PostMapping("download/{name}")
    public R Download(@PathVariable String name){
        fileService.download(name);
        return  R.ok();
    }
    @ApiOperation(value = "浏览器文件下载")
    @GetMapping(value = "/downloads/{name}")
    public void logDownload(@PathVariable String name, HttpServletResponse response) throws Exception {
        fileService.logDownload(name, response);
    }

    @ApiOperation(value = "删除文件")
    @GetMapping("/deleteflie/{filename}")
    public R DeleteFile(@PathVariable String filename){

        String s = fileService.deleteFile(filename);
        return  R.ok().data("状态:",s);
    }

10.输入http://localhost:8083/swagger-ui.html#/测试

Springboot2整合阿里云OSS实现文件上传、下载、删除、查看

Springboot2整合阿里云OSS实现文件上传、下载、删除、查看

其他的可以自行试。网页下载文件需要在浏览器中输入,不要在swagger中测试

上传到阿里云的OSS上有一个地址访问:https://xiaozhuya.oss-cn-beijing.aliyuncs.com/avatar/2020/07/15/c48fc2af-08e6-4e67-a667-ebbe3d6a4b73.jpg   把他放到页面中的<a> 标签中的src就可以显示啦!

本文地址:https://blog.csdn.net/qq_41085151/article/details/107354263