springboot上传图片七牛云(可以多图上传)

// 第一步 七牛云官网配置

 1: 新建存空间
Paste_Image.png

Paste_Image.png
2: 查看accessKey/secretKey:打开七牛云网站 , 登陆后在右上角 {个人面板 --->  选择个人中心--->密钥管理}
springboot上传图片七牛云(可以多图上传)_第1张图片
Paste_Image.png

springboot上传图片七牛云(可以多图上传)_第2张图片
查看accessKey/secretKey

// 第二步 代码上传

① 七牛云配置

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * @author 创建人:< Chenmq>
 * @project 项目:<>
 * @date 创建时间:< 2017/8/30>
 * @comments: 说明:< //七牛云图片配置 >
 */
public class QiniuUtil {

    private static final Logger logger = Logger.getLogger(QiniuUtil.class);



    //设置好账号的ACCESS_KEY和SECRET_KEY
    final String ACCESS_KEY = "YOU_ACCESS_KEY";
    final String SECRET_KEY = "YOU_SECRET_KEY";
    //要上传的空间
    final String BUCKET_NAME = "创建的存储空间名称";

    /**
     * 七牛云上传图片
     * @param localFilePath
     * @return
     */
    public String uoloapQiniu (File localFilePath,String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg;
        cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传
        String accessKey = ACCESS_KEY;
        String secretKey = SECRET_KEY;
        String bucket = BUCKET_NAME;
        //如果是Windows情况下,格式是 D:\23912475_130759767000_2.jpg
//        String localFilePath = "D:\\23912475_130759767000_2.jpg";
        //        String localFilePath = "/home/qiniu/test.png";
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = "images/"+fileName+"?tId="+System.currentTimeMillis();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        String result = null;

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            logger.info("{七牛图片上传key: "+ putRet.key+",七牛图片上传hash: "+ putRet.hash+"}");

            result = "外链域名(如:image.domain.com)"+putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            result = null;
        }
        return result;
    }

}

② 文件上传的service相关

import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @author 创建人:< Chenmq>
 * @project 项目:<>
 * @date 创建时间:< 2017/9/2>
 * @comments: 说明:< //TODO >
 */
public interface FileService {

    /**
     * 多文件上传
     * @param file
     * @return
     */
    Map> uploadImgs(MultipartFile[] file);
}

③ service 实现

import com.data.core.utils.QiniuUtil;
import com.data.web.service.service.upload.FileService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author 创建人:< Chenmq>
 * @project 项目:
 * @date 创建时间:< 2017/9/2>
 * @comments: 说明:< //文件上传 >
 */


@Service
public class FileServiceImpl implements FileService {

    private static final Logger logger = Logger.getLogger(FileServiceImpl.class);


    /**
     * 七牛云上传图片
     * @param file
     * @return
     */
    @Override
    public Map> uploadImgs(MultipartFile[] file) {

        Map> resultMap = new HashMap<>();
        List list = new LinkedList<>();
        String result = null;

        for (int i = 0; i < file.length; i++) {
            String fileName = file[i].getOriginalFilename();

            // 创建一个临时目录文件
            String tempFiles = "temp/"+fileName;
            File dest = new File(tempFiles);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            BufferedOutputStream out = null;
            QiniuUtil qn = new QiniuUtil();

            try {
                out = new BufferedOutputStream(new FileOutputStream(dest));
                out.write(file[i].getBytes());
                result = qn.uoloapQiniu(dest,fileName);

                if (StringUtils.isNotBlank(result)) {
                    list.add(result);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e1) {
                e1.getMessage();
            }  finally{
                try {
                    if (null != out) {
                        out.flush();
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (dest.getParentFile().exists()) {
                    dest.delete();
                }
            }
        }
        logger.info("imagesList == " + list);
        if (list.isEmpty()) {
            list.add("error");
        }
        resultMap.put("result",list);
        return resultMap;
    }
}

④ controller

import com.data.core.ServiceResult;
import com.data.web.service.service.upload.FileService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 创建人:< Chenmq>
 * @project 项目:
 * @date 创建时间:< 2017/8/22>
 * @comments: 说明:< //TODO >
 */

@RestController
@RequestMapping("/admin/webServer")
public class WebServerController {

    private static final Logger logger = Logger.getLogger(WebServerController.class);

    @Resource
    private FileService fileService;


    /**
     * 上传图片文件七牛云
     * @param files
     * @return
     */
    @RequestMapping(value="/imgs", method = RequestMethod.POST)
    public ServiceResult uploadImg(@RequestParam("file") MultipartFile[] files) {

         // 返回类型可以自己定义

        ServiceResult serviceResult = null;

        // 验证非空
        if (StringUtils.isBlank(files[0].getOriginalFilename())) {
            serviceResult = new ServiceResult().dataIsNot();
        } else {
            Map> map = new HashMap<>();

            map = fileService.uploadImgs(files);

            List resultList = map.get("result");
            logger.info("图片上传返回结果:"+resultList);

            if ("error".equals(resultList.get(0))) {
                serviceResult = new ServiceResult().dataIsNot();
            } else {
                serviceResult = new ServiceResult(resultList);
            }
        }
        return serviceResult;
    }
}

配置上传图片大小 (直接在启动类就行)

 /**
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大
        factory.setMaxFileSize("10240KB"); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }
springboot上传图片七牛云(可以多图上传)_第3张图片
启动类

⑤ js层

/**
 * 上传图片
 */

function uploadImg(){

    /**
     * formData在jquey中使用需要设置:
     * processData: false, // 告诉jQuery不要去处理发送的数据
     * contentType: false // 告诉jQuery不要去设置Content-Type请求头
     * @type {null}
     */

    var serverHost = getCookie("serverHost");
    var host = serverHost +"admin/webServer/imgs";
    var fd = new FormData();
    
  // 第一个参数为controller 接收的参数名称 , input的id 
    fd.append("file", document.getElementById("inputId").files[0]);
    $.ajax({
        url:host,
        type:"post",
        data:fd,
        processData:false,
        contentType:false,
        success:function(res){
            console.log(res);

            if (res.status.code == 0) {
                if (!$('#img').empty()) {
                    $('#img').empty();
                }
                // 这一串代码复制不上来 ,截图在下面
                 $('#img').append(" ![](+res.result[0]+)");
            } else {
                alert("图片上传失败");
            }
        },
        dataType:"json"
    })
}

/**
 * 添加cookie
 * @param key
 * @param value
 * @param days 保存时间长度
 */
function setCookie(key,value,days){
    var oDate = new Date();
    oDate.setDate(oDate.getDate() + days);
    document.cookie = key+'='+value+';expires='+oDate;
}

/**
 * 取cookie
 * @param cookieKey
 * @returns {null}
 */
function getCookie(cookieKey) {
    var aCookie = document.cookie.split("; ");
    for (var i= 0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split("=");
        if (cookieKey == aCrumb[0]) {
            return unescape(aCrumb[1]);
        }
    }
    return null;
}
图片显示

⑥ input

 
  

// 对应的jar包在七牛云官网sdk文档寻找
https://developer.qiniu.com/kodo/sdk/1239/java

引入js和jquery

你可能感兴趣的:(springboot上传图片七牛云(可以多图上传))