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:\\Users\\ukyo\\Downloads\\oss-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("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                        strBuf.append(inputValue);
                    } else {
                        strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\""
                                + inputName + "\"\r\n\r\n");
                        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("\r\n").append("--").append(boundary)
                    .append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"file\"; "
                    + "filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type: " + contentType + "\r\n\r\n");

            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 = ("\r\n--" + boundary + "--\r\n").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("\n");
            }
            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;

    }



原文地址:https://www.cnblogs.com/ukzq/p/12105333.html

时间: 2024-11-06 10:32:02

OSS - 表单上传及参数回调的相关文章

node.js学习(2)--路由功能以及表单上传

今天按照<node.js入门>这本书学习了node的一些基础知识,包括服务器的创建,路由功能的实现,表单上传和数据处理,感觉开始明白了node.js的一些基本原理.这本书说的很详细也很基础,很适合初学者学习.node.js入门 众所周知,node跟php语言不一样,node不需要依赖于apache等服务器,因为node本身就能够构建服务器!所以,再用node开发网站之前我们首先得学会如何搭建服务器.关于node创建服务器在我之前的博客已经有介绍,这里不再赘述. 完成一个表单上传与数据处理的de

相册选择头像或者拍照 上传头像以NSData 图片二进制格式 表单上传

一.点击头像图片 或者按钮 在相册选择照片返回img,网络上传头像要用data表单上传 (1)上传头像属性 // 图片二进制格式 表单上传 @property (nonatomic, strong) NSData *imageWithData; (2)头像点击事件 - (void)headImageEvent{ NSLog(@"上传头像"); [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) { self.heade

Android实现模拟表单上传

很久以前,写过一篇关于下载的文章:基于HTTP协议的下载功能实现,今天对于Android上的文件上传,也简单的提两笔.在Android上,一般使用Http 模拟表单或者FTP来进行文件上传,使用FTP协议,可以直接使用Appache的FTPClient,使用方法很简单,不再赘述.这里主要说明一下Http模拟表单上传的实现. 模拟表单上传,其实也很简单,主要需要在Http post 的数据体中构建表单信息(multipart/form),表单数据格式的规范,可以参考REC标准.下面是一个格式示例:

[转]html5表单上传控件Files API

表单上传控件:<input type="file" />(IE9及以下不支持下面这些功能,其它浏览器最新版本均已支持.) 1.允许上传文件数量 允许选择多个文件:<input type="file" multiple> 只允许上传一个文件:<input  type="file" single> 2.上传指定的文件格式 <input type="file" accept="im

利用socket模拟http的混合表单上传(在一个请求中提交表单并上传多个文件)

在很多企业级应用中,我们都没法直接通过开发语言sdk包封装的http工具来模拟http复合表单(multipart/form-data),特别是在跨语言跨平台的编程过程中,其实实现方案并不复杂,只要你了解了http协议中复合表单的报文结构就很简单了: httpheader ------时间戳------ 表单参数1 ------时间戳------ 表单参数2 ------时间戳------ 文件1的描述+二进制信息 ------时间戳------ 文件2的描述+二进制信息 下面我们进一步以一段c

PHP CURL 模拟form表单上传遇到的小坑

1:引用的时候 $parans ['img']=new \CURLFile($param); 传入的文件 在PHP版本5.5以上记得new CURLFile 不然会上传不成功 /** * http post请求--CURL模拟表单上传文件 * @param $url string 请求地址 * @param $params array 请求参数 * @param $header array 请求头 * @return mixed */ protected function _httpPostIm

android form表单上传文件

原文地址:http://menuz.iteye.com/blog/1282097 Android程序使用http上传文件 有时,在网络编程过程中需要向服务器上传文件.Multipart/form-data是上传文件的一种方式. Multipart/form-data其实就是浏览器用表单上传文件的方式.最常见的情境是:在写邮件时,向邮件后添加附件,附件通常使用表单添加,也就是用multipart/form-data格式上传到服务器.  Html代码   <form action="/Test

使用form表单上传文件

在使用form表单上传文件时候,input[type='file']是必然会用的,其中有一些小坑需要避免. 1.form的 enctype="multipart/form-data" 已经是个老生常谈的问题了,相信都能注意到,就不多说了. 2.上传下载的请求是不能用ajax提交返回json的. 3.当使用input[type='file'] 的onChange事件来触发文件上传的时候要注意当上传成功时清空input的时候,不能简单的使用$("input").val(

理解流方式上传和form表单上传

流方式上传: $post_input = 'php://input'; $save_path = dirname( __FILE__ ); $postdata = file_get_contents( $post_input ); if ( isset( $postdata ) && strlen( $postdata ) > 0 ) { $filename = $save_path . '/' . uniqid() . '.jpg'; $handle = fopen( $filen