springboot上传文件和图片至七牛云

引言:一切皆文件

 

用过阿里云对象存储,想换个口味试试

一、七牛云快速入门

快速入门

    1、注册账号
    2、创建存储空间, 命名windseacher-test01,对应下面springboot 应用配置bucket
    3、创建成功后进入该空间,获取该空间的测试域名,对应下面springboot 应用配置中的path
    4、点击“个人面板—密钥管理”,获取 accessKey 和 secretKey
 

要使用七牛云对象存储空间(这是在你已经有了账号的情况下),首先导入依赖

 
            com.qiniu
            qiniu-java-sdk
            7.2.7
        

七牛云相关配置,配置密钥对和存储位置(application.properties)


#七牛云配置
qiniu.accessKey=你的AK
qiniu.secretKey=你的的SK
qiniu.bucket=windsearcher-test01     #存储的位置
qiniu.path=pzr2bm7k7.bkt.clouddn.com  #使用了七牛云提供的测试域名

 配置类,读取application.properties相关的配置

package com.example.demo.util;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/*
* @Author:liqiang
* @Date:2019-10-22
* */
@Component
@ConfigurationProperties(prefix = "qiniu")
public class QiniuUtil {

    private String accessKey;

    private String secretKey;

    private String bucket;

    private String path;

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

配置类

package com.example.demo.config;

import com.example.demo.util.QiniuUtil;
import com.google.gson.Gson;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.MultipartConfigElement;
import javax.servlet.Servlet;
/**
 * @author liqiang
 * @date 2019-10-22
 */
@Configuration
@ConditionalOnClass({Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class})
@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(MultipartProperties.class)
public class FileUploadConfig {
    /**
     * 七牛云配置
     */
    @Autowired
    private QiniuUtil qiNiuProperties;
    private final MultipartProperties multipartProperties;
    public FileUploadConfig(MultipartProperties multipartProperties) {
        this.multipartProperties = multipartProperties;
    }
    /**
     * 上传配置
     */
    @Bean
    @ConditionalOnMissingBean
    public MultipartConfigElement multipartConfigElement() {
        return this.multipartProperties.createMultipartConfig();
    }
    /**
     * 注册解析器
     */
    @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
    @ConditionalOnMissingBean(MultipartResolver.class)
    public StandardServletMultipartResolver multipartResolver() {
        StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
        multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
        return multipartResolver;
    }
    /**
     * 华东   Zone.zone0()
     * 华北   Zone.zone1()
     * 华南   Zone.zone2()
     * 北美   Zone.zoneNa0()
       这里得注意你对象存储空间所在区
     */
    @Bean
    public com.qiniu.storage.Configuration qiniuConfig() {
        //华东
        return new com.qiniu.storage.Configuration(Zone.zone2());
    }
    /**
     * 构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager() {
        return new UploadManager(qiniuConfig());
    }
    /**
     * 认证信息实例
     *
     * @return
     */
    @Bean
    public Auth auth() {
        return Auth.create(qiNiuProperties.getAccessKey(),
                qiNiuProperties.getSecretKey());
    }
    /**
     * 构建七牛空间管理实例
     */
    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth(), qiniuConfig());
    }
    /**
     * 配置gson为json解析工具
     *
     * @return
     */
    @Bean
    public Gson gson() {
        return new Gson();
    }
}

上传文件接口service类

package com.example.demo.service;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;

import java.io.File;
/**
 * @author liqiang
 * @date 2019-10-22
 */
public interface UploadService {
    /**
     * 上传文件
     * @param file File
     * @return
     * @throws QiniuException
     */
    Response uploadFile(File file) throws QiniuException;
}

serviceImpl

package com.example.demo.serviceImpl;


import com.example.demo.service.UploadService;
import com.example.demo.util.QiniuUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @author liqiang
 * @date 2019-10-22
 */
@Service
public class UploadServiceImpl implements UploadService, InitializingBean {
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private Auth auth;
    @Autowired
    private QiniuUtil qiNiuProperties;
    private StringMap putPolicy;
    String key = null;
    @Override
    public Response uploadFile(File file) throws QiniuException {
        Response response = this.uploadManager.put(file, key, getUploadToken());
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(file, key, getUploadToken());
            retry++;
        }
        return response;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }
    /**
     * 获取上传凭证
     *
     * @return
     */
    private String getUploadToken() {
        return this.auth.uploadToken(qiNiuProperties.getBucket(), null, 3600, putPolicy);
    }
}

controller类

package com.example.demo.controller;

import com.example.demo.serviceImpl.UploadServiceImpl;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.model.DefaultPutRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FileController {

    @Autowired
    private UploadServiceImpl uploadService;
    /**
     * 接受post方法,将表单传来的数据插入
     * @return 服务端跳转到announce.html
     */
    @PostMapping("/addContent")
    public String addContent(HttpServletRequest request,@RequestParam("file") MultipartFile file, Model model){
        try{
            //得到文件名
            String fileName = file.getOriginalFilename();

     
            Response response = uploadService.uploadFile(new File(fileName));
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        }catch (IOException e){
            e.printStackTrace();
        }

        return "ok";
    }

}

 

前端测试下:



 
  
  
  
  
  
  Document
 
 
  

 

你可能感兴趣的:(springboot)