2017-10-04 24 views
-4

我是新来的打字稿,并尝试从移动SD卡上传图片。浏览图像时,我正在获取图像路径。当我通过这个表单数据时,无返回。如果有人帮助解决问题,这将是非常棒的。使用移动表单数据的打字稿图片上传返回无

我使用“nativescript-imagepicker”库从SD卡获取图像..

sendPicture(uri: string, modelContext: any){ 
    let _formData = new FormData(); 
    _formData.append("profile_image", uri); 
    let body = _formData; 
    updateAvatarService(this.userToken,body).subscribe(data => { 
    }); 
} 

updateAvatarService(token,body): Observable<any> { 
      return this.httpClass.patchMethodWithToken(URL,token,body) 
      .map(response => { 
      return response; 
      }) 
    } 

patchMethodWithToken(url: string, token: string, data: Object) { 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    headers.append('Authorization', "Token " + token); 
    headers.append('Content-Disposition', "form-data");  
     let options = new RequestOptions({ headers: headers }); 
    if (this.checkNetworkConnection()) { 
     return this.http 
     .patch(url, JSON.stringify(data), options) 
     .map(response => { 
      return response.json(); 
     }) 
     .catch(this.handleErrors); 
    } 
    } 
+0

提供代码 – Dlucidone

+0

更多信息请检查我现在已经增加了代码.. – vishnuc156

回答

1

对于多上传的表单数据我是用Nativescript背景-HTTP 下面是示例实现,它为我工作 -

import { session, Session, Task } from "nativescript-background-http"; 
var session1 = session("image-upload"); 

uploadImage(fileUri, id) { 

let imageName = this.extractImageName(fileUri); 
let headers = new Headers(); 
headers.append("Authorization", Config.token); 
headers.append("CenterId", Config.CenterId); 
var options = new RequestOptions({ headers: headers }); 
var request = { 
    url: Config.putImage + id + "/upload", 
    method: "POST", 
    headers: { 
    "Authorization": Config.token, 
    "X-Center-Id": Config.XCenterId, 
    "Content-Type": "application/octet-stream", 
    "File-Name": imageName 
    }, 

    description: "{ 'uploading': " + imageName + " }" 
}; 
var params = [{ name: "image", filename: fileUri, mimeType: 'image/jpeg' }]; 
var task = session1.multipartUpload(params, request); 
task.on("progress", logEvent); 
task.on("error", logEvent); 
task.on("complete", logEvent); 

function logEvent(e) { 
    console.log(".........................") 
    console.log("currentBytes: " + e.currentBytes); 
    console.log(".........................") 
    console.log("totalBytes: " + e.totalBytes); 
    console.log(".........................") 
} 

return task; 
} 

//Extract file Name 
extractImageName(fileUri) { 
var pattern = /[^/]*$/; 
var imageName = fileUri.match(pattern); 
return imageName; 
} 
+0

感谢Dlucidone。 我的服务器使用PATCH方法,身为formadata,其关键字为“profile_image”:“img_name.png”。 我的问题是如何将这个正文传递给上面的代码? – vishnuc156

+0

使用方法:“PATCH”和“File-Name”:img_name“并将其传递给 - >此函数uploadImage(fileUri,method_name,oranything) – Dlucidone