OSS - 表单上传及参数回调

Posted ukzq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OSS - 表单上传及参数回调相关的知识,希望对你有一定的参考价值。

表单上传是通过web表单form的形式直接将文件上传到OSS

其中回调参数跟以往不同,需要另外设定.

aliyun官方很多个demo代码,但唯一有效的是

package com.springboot.oss.service;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */


import javax.activation.MimetypesFileTypeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * This sample demonstrates how to post object under specfied bucket from Aliyun
 * OSS using the OSS SDK for Java.
 */
public class PostObjectSample {

    // The local file path to upload.
    private String localFilePath = "C:UsersukyoDownloadsoss-work.png";
    // OSS domain, such as http://oss-cn-hangzhou.aliyuncs.com
    private String endpoint = "http://oss-cn-heaven.aliyuncs.com";
    // Access key Id. Please get it from https://ak-console.aliyun.com
    private String accessKeyId = "NICAICAIKANBa";
    private String accessKeySecret = "woJIUBUGAOSUNIHEHEHEHEHeeee";
    // The existing bucket name
    private String bucketName = "sugar-1";
    // The key name for the file to upload.
    private String key = "oss-work.png";

    private void postObject() throws Exception {
        // append the ‘bucketname.‘ prior to the domain, such as http://bucket1.oss-cn-hangzhou.aliyuncs.com.
        String urlStr = endpoint.replace("http://", "http://" + bucketName + ".");

        // form fields
        Map<String, String> formFields = new LinkedHashMap<String, String>();

        // key
        formFields.put("key", this.key);
        // Content-Disposition
        formFields.put("Content-Disposition", "attachment;filename="
                + localFilePath);
        // OSSAccessKeyId
        formFields.put("OSSAccessKeyId", accessKeyId);
        // policy
        String policy
                = "{"expiration": "2120-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 104857600]]}";
        String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
        formFields.put("policy", encodePolicy);
        // Signature
        String signaturecom = computeSignature(accessKeySecret, encodePolicy);
        formFields.put("Signature", signaturecom);
        // Set security token.
//        formFields.put("x-oss-security-token", "<yourSecurityToken>");

        String ret = formUpload(urlStr, formFields, localFilePath);

        System.out.println("Post Object [" + this.key + "] to bucket [" + bucketName + "]");
        System.out.println("post reponse:" + ret);
    }

    private static String computeSignature(String accessKeySecret, String encodePolicy)
            throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        // convert to UTF-8
        byte[] key = accessKeySecret.getBytes("UTF-8");
        byte[] data = encodePolicy.getBytes("UTF-8");

        // hmac-sha1
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(key, "HmacSHA1"));
        byte[] sha = mac.doFinal(data);

        // base64
        return new String(Base64.encodeBase64(sha));
    }

    private static String formUpload(String urlStr, Map<String, String> formFields, String localFile)
            throws Exception {
        String res = "";
        HttpURLConnection conn = null;
        String boundary = "9431149156168";

        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            // Set Content-MD5. The MD5 value is calculated based on the whole message body.
//            conn.setRequestProperty("Content-MD5", "<yourContentMD5>");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // text
            if (formFields != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Entry<String, String>> iter = formFields.entrySet().iterator();
                int i = 0;

                while (iter.hasNext()) {
                    Entry<String, String> entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();

                    if (inputValue == null) {
                        continue;
                    }

                    if (i == 0) {
                        strBuf.append("--").append(boundary).append("
");
                        strBuf.append("Content-Disposition: form-data; name=""
                                + inputName + ""

");
                        strBuf.append(inputValue);
                    } else {
                        strBuf.append("
").append("--").append(boundary).append("
");
                        strBuf.append("Content-Disposition: form-data; name=""
                                + inputName + ""

");
                        strBuf.append(inputValue);
                    }

                    i++;
                }
                out.write(strBuf.toString().getBytes());
            }

            // file
            File file = new File(localFile);
            String filename = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("
").append("--").append(boundary)
                    .append("
");
            strBuf.append("Content-Disposition: form-data; name="file"; "
                    + "filename="" + filename + ""
");
            strBuf.append("Content-Type: " + contentType + "

");

            out.write(strBuf.toString().getBytes());

            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();

            byte[] endData = ("
--" + boundary + "--
").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            // Gets the file data
            strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("
");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.err.println("Send post request exception: " + e);
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

        return res;
    }

    public static void main(String[] args) throws Exception {
        PostObjectSample ossPostObject = new PostObjectSample();
        ossPostObject.postObject();
    }

}

这里设定回调时,可以把生成Callback实例操作放到其他地方

通过map集合传递

    public static Callback setFormCallBackArgments(Map<String, Object> argsMap) {

        //上传回调参数
        Callback callback = new Callback();

//        callback.setCallbackBody(callBackBody);
        if (callBackBodyType.equals("json")) {
            callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
        } else if (callBackBodyType.equals("url")) {
            callback.setCalbackBodyType(Callback.CalbackBodyType.URL);
        }
        //回调参数
        String callBackVarMapsJson = "";
        String callBackVarMapsJson1 = (String) argsMap.get("callBackVarMapsJson");
        if (callBackVarMapsJson1 != null) {
            callBackVarMapsJson = (String) argsMap.get("callBackVarMapsJson");
            argsMap.remove("callBackVarMapsJson");
        }
//        argsMap.get("formUploadEntity").toString();
        String formUploadEntity = JSON.toJSONString(argsMap.get("formUploadEntity"));
        System.out.println("formUploadEntity:" + formUploadEntity);
        Map<String, String> formUploadEntityMapJson = new HashMap<>();
//        formUploadEntityMapJson.put("formUploadEntityMapJson", formUploadEntity.toString());
        String callBackBody = "callbackStr=" + "你好世界";
//        String s = argsMap.toString();
//        System.out.println("s:::::" + s);
//        String replaceS = formUploadEntity.substring(1, formUploadEntity.length() - 1).replace(", ", "&");
//        replaceS = replaceS.replace("", "\\");

//        replaceS = replaceS.replace("http://", "");
//        if (callBackVarMapsJson.length() != 0) {
//            replaceS += "&callBackVarMapsJson=" + callBackVarMapsJson;
//        }
        callback.setCallbackUrl(callBackStrUrl);
        callback.setCallbackHost(callBackHost);
        callback.setCallbackBody(callBackBody);

        return callback;

    }技术图片

 

 


 

以上是关于OSS - 表单上传及参数回调的主要内容,如果未能解决你的问题,请参考以下文章

ajaxFileUpload上传带参数文件及JS验证文件大小

Ali OSS服务端签名直传并设置上传回调

javascript 上传文件到阿里云的oss,上传文件成功后怎么获取文件的真实路径?

阿里云OSS使用RAM生成STS分片上传大文件Demo

阿里云OSS使用RAM生成STS分片上传大文件Demo

在OneThink(ThinkPHP3.2.3)中整合阿里云OSS的PHP-SDK2.0.4,实现Web端直传,服务端签名直传并设置上传回调的实现流程