【问题标题】:AngularJS / PHP API-Backend Image UploadAngularJS / PHP API-后端图片上传
【发布时间】:2018-11-11 16:36:13
【问题描述】:

我正在尝试将图像上传到我的 PHP web-API。在邮递员中,一切工作正常,如果我使用密钥 profilePicture 和作为文件的值(我的 API 在处理之前检查所有内容)进行 POST 请求,则保存图像。 但是现在,我想使用 AngularJS 进行上传,但我一直收到 500 响应。这是我的前端代码:(我需要清理代码,我知道,它关于现在的功能)

<form class="updateUserInformation"
                      ng-submit="updateProfile(userData.display_name,
                                               userData.profile_picture,
                                               account.username)"
                      flex="100" layout="row" >
                <div>
                    <input ng-model="userData.profile_picture" type="file">
                    <img src=""
                         width="150px" style="border-radius: 20px">
                </div>
                <div>

                    <md-input-container class="md-block">
                        <label>Schermnaam</label>
                        <input type="text" ng-model="userData.display_name" width="100%" required autofocus>
                    </md-input-container>
                    <div>
                        <md-button class="md-button md-primary md-raised" type="submit">Submit</md-button>
                    </div>
                </div>
                </form>

这是我的控制器:

controller('profileController', function($scope) {
    $scope.updateProfile = function (display_name, profile_picture, id) {

        console.log(profile_picture);

        var xhr = new XMLHttpRequest();
        var url = '';
        xhr.open('PUT', url, false);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify({displayName:display_name}));

        var xhr2 = new XMLHttpRequest();
        var url2 = '';
        xhr2.open('POST', url2, true);
        xhr2.setRequestHeader("Content-Type", "multipart/form-data");
        xhr2.send(JSON.stringify({profilePicture:profile_picture}));

        // location.reload();
    }
});

【问题讨论】:

    标签: angularjs xmlhttprequest image-uploading


    【解决方案1】:

    要使用 Ajax 上传文件,请使用 FormData 对象

        var xhr2 = new XMLHttpRequest();
        var url2 = '';
        xhr2.open('POST', url2, true);
        var data = new FormData();
        data.append('profilePicture', profile_picture);// profile_picture is a File or a Blob
        // don't set the Content-Type header, it will be set internally(when FormData is used)
        xhr2.send(data);
    

    FormData
    File
    Blob

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 2014-07-11
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2014-06-02
      相关资源
      最近更新 更多