java(SSM)上傳文件到七牛雲(對象存儲)

項目中會用到大量的圖片和小視頻,爲了分擔服務器壓力,將文件都放在七牛雲。這裏的思路很簡單,html

就是移動端、pc端把文件上傳到服務器,服務器作一個臨時緩存,保存必要的信息到數據庫後,前端

將文件上傳到七牛雲,最後刪除服務器的緩存。固然,也能夠直接讓移動端、pc端把文件上傳到七牛雲,java

七牛雲在返回信息給服務器,這種方法雖然更佳,可是敲起代碼來有點麻煩,複雜。 jquery

首先咱們獲得七牛雲官網建立屬於本身的空間ios

實名認證最後有大內存ajax

登錄官網申請帳號,而後創建對象儲存空間Bucket 。數據庫

 

 

做爲練習創建公開空間便可json

 

 

若創建私有的將採起支付寶受權,受權後受到以下郵件信息axios

 

 

 

以後進入創建的空間則能看見相關信息七牛雲存儲

 

 

前期的準備工做大體就完成了。

本文章以Maven爲Demo

在pom.xml中咱們須要引入SDK

 <!-- 七牛雲 -->
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>qiniu-java-sdk</artifactId>
      <version>7.1.1</version>
    </dependency>

而後咱們建立一個七牛雲工具類

package com.dz147.Util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.IOException;

public class QiniuUtil {
    //設置須要操做的帳號的AK和SK
    private static final String ACCESS_KEY = "";
    private static final String SECRET_KEY = "";

    //要上傳的空間
    private static final String bucketname = "picturestorage";

    //密鑰
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    //普通上傳
    public void upload(String filePath, String fileName) throws IOException {
        //建立上傳對象
        UploadManager uploadManager = new UploadManager();
        try {
            //調用put方法上傳
            Response res = uploadManager.put(filePath, fileName, auth.uploadToken(bucketname));
            //打印返回的信息
            System.out.println(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 請求失敗時打印的異常的信息
            //System.out.println(r.toString());
            try {
                //響應的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
    }
}

查看密匙

使用是這麼一個思路首先前端咱們傳一個文件到後臺(以添加圖片爲例)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    </style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
    選擇要上傳的文件:<br/>
    <input type="file" name="file" id="myFile"/><span></span>
</form>
<div id="bar">
    上傳進度:
    <progress id="pro" value="0"></progress>
</div>
<input type="button" id="upLoadSub" value="上傳"/>
<div>
    <img src="" alt="GG" id="myImg" width="200" height="160"/>
</div>

</body>
<script src="../js/jquery.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>


    var myFile = document.getElementById("myFile");
    //綁定事件(ECMAScript6寫法)
    myFile.addEventListener("change", () => {
        var file = myFile.files[0];
        //預覽圖片函數
        previewWithObjectURL(file);
    })
    //點擊->圖片上傳   //axios輕量級 ajax API
    $("#upLoadSub").on("click", function () {
        var myFile = document.getElementById("myFile");
        var formData = new FormData();
        formData.append("file", myFile.files[0]);
        axios({
            method: 'post',
            url: '/addQiniu',
            data: formData
        }).then(function (response) {
            console.log(response.data);
        }).catch(console.error);
    });


    //簡單的圖片預覽建議使用第一種方式
    //URL方式(第一種方式)src = blob:http://localhost:8080/f720711f-57e2-428f-8a47-ec59e5dbbc10
    function previewWithObjectURL(file) {
        var url = URL.createObjectURL(file);
        var reader = new FileReader();
        reader.readAsDataURL(file);
        //請求完成後,顯示圖片
        reader.onloadend = function (event) {
            document.getElementById("myImg").src = url;
        }
        //上傳過程當中動態顯示進度條
        reader.onprogress = function (event) {
            if (event.lengthComputable) {
                document.getElementById("pro").value = event.loaded / event.total;
            }
        }
    }
</script>
</html>

先把文件添加到image目錄裏

添加到後臺服務器獲得文件資源再往七牛雲添加。

//Controller部分
@RequestMapping(value = "/addQiniu", method = RequestMethod.POST, produces = "application/json;charset=utf-8;")
    public @ResponseBody
    String qiniuyunAdd(MultipartFile file, Model model, HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath(File.separator + "imges");
        String qiniuPath = "";
        try {
            //上傳文件方法返回重命名,文件名稱
            String s = excels.upLoadImg(file, realPath);
            //添加成功後的絕對路徑
            String thisPath = realPath + File.separator + s;
            //組合七牛雲外鏈(七牛雲生成域名+保存的文件KEY)
            qiniuPath = "http://pjv3h15g0.bkt.clouddn.com/" + s;
            QiniuUtil qiniuUtil = new QiniuUtil();
            //添加到七牛雲
            qiniuUtil.upload(thisPath, s);
            System.out.println(s + ",項目文件路徑:" + thisPath + ",七牛雲存儲路徑:" + qiniuPath);
            File file1 = new File(thisPath);
            if (file1.isFile()) {
                //刪除服務器圖片
                file1.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return qiniuPath;
    }

服務器添加圖片的相關API

 @Override
    public String upLoadImg(MultipartFile file, String path) throws IOException {
        ArrayList<String> strings = new ArrayList<>();
        if (file.isEmpty()) {
            strings.add("請選擇文件!");
        }
        //獲得文件的類型
        String fileType = file.getContentType();
        //第一種方式Arrays.asList("image/jpeg","image/png")
        if (!fileType.contains("image/")) {
            strings.add("只容許上傳圖片!");
        }
        //只容許上傳的圖片小於5MB
        log.info(file.getSize());
        if (file.getSize() > 1024 * 1024 * 1024 * 5) {
            strings.add("只容許上傳5M的圖片!");
        }
        String fileName = "";

        String[] formatName = getFormatName(file.getOriginalFilename());
        file.transferTo(new File(path + File.separator + formatName[0] + formatName[1] + formatName[2]));
        //獲得圖片的相對路徑
        fileName = formatName[0] + formatName[1] + formatName[2];

        if (strings.size() > 0) {
            fileName = "";
            fileName = strings.get(0);
        }
        return fileName;
    }

    public String[] getFormatName(String fileName) {
        //設置日期格式yyyy-MM-dd
        SimpleDateFormat df = new SimpleDateFormat("_yyyyMMddHHmmss");
        // new Date()爲獲取當前系統時間
        String now = df.format(new Date());
        //得到文件名去掉後綴
        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
        //獲得文件後綴帶.
        String postfix = fileName.substring(fileName.lastIndexOf("."));
        return new String[]{prefix, now, postfix};
    }

結合自身需求的總結

相關文章
相關標籤/搜索