add: http.postMultipart

This commit is contained in:
hyb1996
2017-12-05 17:59:42 +08:00
parent 0473dfbf60
commit e9346f0794
11 changed files with 167 additions and 11 deletions

View File

@@ -30,6 +30,14 @@ module.exports = function(runtime, scope){
return http.post(url, data, options, callback);
}
http.postMultipart = function(url, files, options, callback){
options = options || {};
options.method = "POST";
options.contentType = "multipart/form-data";
options.files = files;
return http.request(url, options, callback);
}
http.request = function(url, options, callback){
var call = http.client().newCall(http.buildRequest(url, options));
if(!callback){
@@ -56,12 +64,53 @@ module.exports = function(runtime, scope){
}
if(options.body){
r.method(options.method, parseBody(options, options.body));
}else{
}else if(options.files){
r.method(options.method, parseMultipart(options.files));
}else {
r.method(options.method, null);
}
return r.build();
}
function parseMultipart(files){
var builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
for(var key in files){
if(!files.hasOwnProperty(key)){
continue;
}
var value = files[key];
if(typeof(value) == 'string'){
builder.addFormDataPart(key, value);
continue;
}
var path, mimeType, fileName;
if(typeof(value.getPath) == 'function'){
path = value.getPath();
}else if(value.length == 2){
fileName = value[0];
path = value[1];
}else if(value.length >= 3){
fileName = value[0];
mimeType = value[1]
path = value[2];
}
var file = new com.stardust.pio.PFile(path);
fileName = fileName || file.getName();
mimeType = mimeType || parseMimeType(file.getExtension());
builder.addFormDataPart(key, fileName, RequestBody.create(MediaType.parse(mimeType), file));
}
return builder.build();
}
function parseMimeType(ext){
if(ext.length == 0){
return "application/octet-stream";
}
return android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)
|| "application/octet-stream";
}
function fillPostData(options, data){
if(options.contentType == "application/x-www-form-urlencoded"){
var b = new FormBody.Builder();
@@ -89,6 +138,8 @@ module.exports = function(runtime, scope){
function parseBody(options, body){
if(typeof(body) == "string"){
body = RequestBody.create(MediaType.parse(options.contentType), body);
}else if(body instanceof RequestBody){
return body;
}else{
body = new RequestBody({
contentType: function(){

View File

@@ -51,6 +51,7 @@ public class RhinoJavaScriptEngine extends JavaScriptEngine {
mAndroidContext = context;
mContext = createContext();
mScriptable = createScope(mContext);
}
@Override