1. 程式人生 > 實用技巧 >從瀏覽器上傳檔案並提交到雲服務提供商

從瀏覽器上傳檔案並提交到雲服務提供商

從瀏覽器上傳檔案並提交到雲服務提供商

程式碼是專案:https://github.com/JiaDingCN/MyBBS 的一部分

這裡用的是七牛雲

Controller層這樣寫:

    /**
     * @Description: 修改使用者頭像
     * @前端示例程式碼: <form action="http://localhost:8080/user/uploadHeadPortrait" method="post" enctype="multipart/form-data">
     * 選擇檔案:<input type="file" name="file" width="120px">
     * <input type="submit" value="上傳">
     * </form>
     * @Param: 只接受post請求
     * 本使用者id從session中獲取,不用傳入
     * 不需要上傳檔名稱
     * @return: void
     * @Author: Yishiyu
     * @Date: 2020/7/19
     */
    @RequestMapping(value = "/uploadHeadPortrait", method = RequestMethod.POST)
    public void uploadHeadPortrait(MultipartFile file, HttpServletRequest req,HttpServletResponse resp) throws IOException {
        InputStream inputStream = file.getInputStream();
        String head_portrait = QiniuyunUtil.uploadObject(inputStream);
        User user = (User) req.getSession().getAttribute("user");
        user.setHead_portrait(head_portrait);
        service.updateUser(user);
        writeValue(ResultInfo.getTrueResultInfo(),resp);
    }

QiniuyunUtil.java

package com.jiading.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class QiniuyunUtil {
    private static final String dataFile = "qiniuyun.properties";

    private static String ACCESS_KEY;
    private static String SECRET_KEY;
    private static String BUCKET_NAME;
    private static String SERVER_DOMAIN;

    private static Configuration cfg;
    private static UploadManager uploadManager;
    private static Auth auth;
    private static String upToken;

    // 從配置檔案中讀取配置
    static {
        Properties properties = new Properties();
        // 使用ClassLoader載入properties配置檔案生成對應的輸入流
        InputStream in = QiniuyunUtil.class.getClassLoader().getResourceAsStream(dataFile);
        // 使用properties物件載入輸入流
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //獲取key對應的value值
        ACCESS_KEY = properties.getProperty("access_key");
        SECRET_KEY = properties.getProperty("secret_key");
        BUCKET_NAME = properties.getProperty("bucket_name");
        SERVER_DOMAIN = properties.getProperty("server_domain");

        //構造一個帶指定 Region 物件的配置類
        cfg = new Configuration(Region.huanan());
        // 配置資訊(略)
        uploadManager = new UploadManager(cfg);
        auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        upToken = auth.uploadToken(BUCKET_NAME);
    }

    /**
     * 獲取雲端儲存伺服器域名
     *
     * @return 域名
     */
    public static String getServerDomain() {
        return SERVER_DOMAIN;
    }

    /**
     * 上傳一個本地檔案到伺服器上
     *
     * @param : String ==> 絕對檔案路徑
     *          Byte[] ==> 位元組陣列
     *          InputStream ==> 輸入流物件中的流
     * @return 如果成功, 返回檔名稱, 如果失敗, 返回空字串
     */
    public static String uploadObject(Object object) {
        //預設不指定key的情況下,以檔案內容的hash值作為檔名
        String key = null;
        DefaultPutRet putRet = null;
        try {
            Response response = null;
            if (object instanceof String) {
                response = uploadManager.put((String) object, key, upToken);
            } else if (object instanceof byte[]) {
                response = uploadManager.put((byte[]) object, key, upToken);
            } else if (object instanceof InputStream) {
                response = uploadManager.put((InputStream) object, key, upToken, null, null);
            }

            //解析上傳成功的結果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                ex2.printStackTrace();
            }
        }
        if (putRet == null) {
            return "";
        }
        return SERVER_DOMAIN + putRet.key;
    }

}