Baidu webuploader upload to Ali OSS

After signing on the server, upload
https://help.aliyun.com/document_detail/31926.html?spm=5176.product31815.6.614.HI0PNh

picture using
https://help.aliyun.com/document_detail/44688.html?spm =5176.doc44686.6.924.t5CtYr

java background signature

package wrules;

import java.io.IOException;
import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
@WebServlet(asyncSupported = true)
public class PostObjectPolicy extends HttpServlet{
	/**
	 *
	 */
	private static final long serialVersionUID = 5522372203700422672L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	    String endpoint = "oss-cn-beijing.aliyuncs.com/";
        String accessId = "Modify";
        String accessKey = "Modify";
        String bucket = "Modify";
        
        String dir = "user-dir";
        if(null!= request.getParameter("dir")){
        	dir = request.getParameter("dir");
        }
        String host = "http://" + bucket + "." + endpoint;
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        try { 	
        	long expireTime = 30;
        	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //respMap.put("expire", formatISO8601Date(expiration));
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            JSONObject ja1 = new JSONObject(respMap);
            System.out.println(ja1.toString());
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
            response(request, response, ja1.toString());
            
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
	
	private void response(HttpServletRequest request, HttpServletResponse response, String results) throws IOException {
		String callbackFunName = request.getParameter("callback");
		if (callbackFunName==null || callbackFunName.equalsIgnoreCase(""))
			response.getWriter().println(results);
		else
			response.getWriter().println(callbackFunName + "( "+results+" )");
		response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
		doGet(request, response);
    }
}


javascript global parameters

var objdata = {
upfile_endpoint:'http://modify.oss-cn-beijing.aliyuncs.com',//Upload address
upfile_nametype:'random_name',//local_name random_name The file name type of the uploaded file
upfile_defaltdir:'upload/CCCC'//Upload path multi-layer format upload/floder1/floder2
};



uploader.on('uploadBeforeSend', function (obj, data, headers) {
  //TODO If the same page is uploaded multiple times, the signature logic needs to be processed without signing each time
	$.ajax({
	     type : "post",
	     url : "osssignuature",
		timeout : 10000,
		data : {
			"dir" : objdata.upfile_defaltdir
		},
		success : function(str) {
			if (str) {
				try {
					var re = JSON.parse(str);				                           objdata.os ssignature = {
										'key' : re.dir, 'policy': re.policy,
								        'OSSAccessKeyId': re.accessid,
								        'success_action_status' : '200', //Let the server return 200, otherwise, it will return 204 by default
								        'signature': re.signature
};
				} catch (e) {
					alert("System error");
				}
				
			} else {
				alert("result is empty");
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert("ajax error");
		},
		complete : function(XMLHttpRequest,status){ //Final execution parameters after the request is completed
			if(status == 'timeout'){
				alert('The request timed out, please try again later!');
			}
		},
		async : false
	});
					
	//assign parameters
	data = $.extend(data,objdata.osssignature);
	//set file path
	data.key = data.key + "/" + calculate_object_name(data.name,objdata.upfile_nametype);
	obj.filepath = data.key;
	file.path = data.key;
	headers['Access-Control-Allow-Origin'] = "*";
});

After uploading the effect

 
source code download
addresshttp ://download.csdn.net/detail/qinghechaoge/9712694

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327037399&siteId=291194637