将图像上传ajax与表单提交ajax相结合

Combine image upload ajax with form submit ajax

本文关键字:ajax 相结合 表单提交 图像      更新时间:2023-09-26

我有像这样的图像上传ajax

$scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log(file);
    var uploadUrl = "/api/upload_image";//It will also goes to '/api/get_data'
    //fileUpload.uploadFileToUrl(file, uploadUrl);
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(e){
        console.log("Success");
    })
    .error(function(e){
        console.log("Error");
    });
};

并像这样调用提交表单ajax。

$http({
    url: "/api/get_data",
    method: "POST",
    dataType:"json",
    data:JSON.stringify(this.formData)
}).success(function(data) {
    console.log("Success");      
}).error(function(error) {
    console.log("Error");
});

两者都是分开工作的,如何将这两个ajax合并为一个,即提交ajax,第二个。

或者有没有任何方法可以在第二个ajax中发布图像数据,我使用的是angular+laravel5.2

我在角度视图中输入的文件是

<input type="file" file-model="myFile">

谢谢。

你可以像这样将这两个ajax结合起来,发布image和formData,试试这个。

var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
fd.append('formData', JSON.stringify(this.formData));

$http({
    url: "/api/get_data",
    method: "POST",
    dataType:"json",
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined},
    data:fd
}).success(function(data) {

要检索formData,您需要在服务器端脚本中解码json。