2017-10-04 23 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