javascript - 结合图片上传ajax和表单提交ajax

标签 javascript angularjs ajax forms

我有这样的图片上传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

我在 Angular View 中的文件输入是

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

谢谢。

最佳答案

你可以像这样组合这两个 ajax,发布图像和 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。

关于javascript - 结合图片上传ajax和表单提交ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37314768/

相关文章:

javascript - Vue JS "PROP MUTATING"用于上传图像

jquery - 在 jQuery 中插入后更新 DOM

javascript - Netsuite Script beforeLoad 记录未被修改

Javascript 全局 onclick 监听器

javascript - 解决 Angular 资源 promise

javascript - 无法读取未定义错误的属性 'push'?

javascript - 使用 Ajax 和 PHP 将文件上传到数据库

JavaScript 错误,未捕获的类型错误

javascript - 如何显示分数计数,显示随机生成的次数?

javascript - 如何将指令模型绑定(bind)到异步服务数据