【问题标题】:Combine image upload ajax with form submit ajax结合图片上传ajax和表单提交ajax
【发布时间】:2016-05-19 05:44:34
【问题描述】:

我有这样的图片上传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合二为一,即submit ajax,第二个。

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

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

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

谢谢。

【问题讨论】:

  • 有两个不同的url。因此,将一个与另一个结合起来可能不是理想的选择。相反,您可以使用 Promise 并链接多个 Promise
  • @user2181397 对于不同的 url,我很抱歉,我需要它作为一个 url /api/get_data
  • 你上传的图片是什么格式的?你想建立什么?您网站的图片上传器?
  • @AlanSutherland,我正在尝试使用任何格式的图像的正常表单数据提交图像。
  • 好的,您可能需要先将其分解为二进制,您将其提交到哪里?

标签: javascript angularjs ajax forms


【解决方案1】:

你可以像这样组合这两个 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。

【讨论】:

    猜你喜欢
    • 2013-06-22
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2020-06-07
    相关资源
    最近更新 更多