2016-09-26 76 views
3

我面临的问题后图像从Ionic /科尔多瓦应用程序,JavaScript的web api。 我参考下面 link将文件图像附加到JavaScript中的FormData(Http请求)

链路这是我的代码:

$http({ 
         method: "POST", 
         url: url, 
          headers: { 
          //'Content-Type': 'multipart/form-data', 
          //'Content-Type': false, 
          //'Content-Type': undefined, 
          'Cache-Control': 'no-cache', 
          'DevicePassword': localStorage.getItem("UserPassword"), 
          'UserName': 'thuong' 
          }, 
          transformRequest: function (data) { 
          var formData = new FormData(); 
          formData.append("data", angular.toJson(data.data)); 
          alert("sizeofImg: " + data.files.length); 

          for (var i = 0; i < data.files.length; i++) { 
           alert(data.files[i].ImgSrc); 
           var blob = dataURItoBlob(data.files[i].ImgSrc); 
           //var file = new File([blob], "file.png",{type: 'image/png'); 
           formData.append("file" + i, blob, "filename" + i + "png"); 
          } 
          return formData; 
          }, 
          data: { data: jsonData, files: files } 
          }) 
      .then(function (result) { 
        alert("success" + result); 
        success(result); 
      }, 
        function (error) { 
        alert("error" + JSON.stringify(error)); 
        failure(error); 
        } 
      ); 

function dataURItoBlob(dataURI) { 
// convert base64/URLEncoded data component to raw binary data held in a string 
var byteString; 
if (dataURI.split(',')[0].indexOf('base64') >= 0) 
    byteString = atob(dataURI.split(',')[1]); 
else 
    byteString = unescape(dataURI.split(',')[1]); 

// separate out the mime component 
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; 

// write the bytes of the string to a typed array 
var ia = new Uint8Array(byteString.length); 
for (var i = 0; i < byteString.length; i++) { 
    ia[i] = byteString.charCodeAt(i); 
} 

return new Blob([ia], {type:mimeString}); 

}

在那里,data.files [I] .ImgSrc是BASE64字符串。 (我用科尔多瓦相机插件得到它) 它的开始像:data:image/png; base64,... 它总是落在失败回调,状态码:415(UnsupportMediaFile)。我实现了服务器端像上面的链接。 dataURIToBlob方法是否正确? 请帮帮我。

回答

1

追加上传文件见代码吹塑

$scope.updateProfile = function(form_data){ 
     console.log(form_data); 
     $scope.submitted = true; 
     $scope.reg = form_data; 
     var fd = new FormData(); 
     var file = $scope.fileToUpload; 
     fd.append('file',file); 
     $http.post(API_URL+"user_update_profile", fd, { 
      transformRequest: angular.identity, 
      headers: {'Content-Type': undefined} 
      }) 
      .success(function(res){ 
       console.log(res); 
      }) 
      .error(function(err){ 
       console.log(err); 
      }); 
    } 

注:fileToUpload变量是文件属性

var file = $scope.fileToUpload; 
    fd.append('file',file); 
+0

我只BASE64串,我不使用组分<输入吨类型= “文件”/> 。 $ scope.fileToUpload在哪里? –

+0

使用文件属性代码上面的代码应用这个没有base64字符串的文件属性,这可以工作。 –

+0

对不起。我不使用输入标签,导致我的任务是从相机插件获取图像。所以我只有base 64.我将它转换为BLOB,现在我不知道如何发布它。 –

相关问题