首页 > 解决方案 > 我正在尝试使用 angularjs 1.6.5 将文件上传到 Django 服务器。我无法使用 $http.patch 方法上传文件

问题描述

使用 Angularjs 1.6.5 我正在尝试将文件上传到 Django 服务器。当我尝试上传文件时,我不确定应该使用 $http.patch 方法传递什么类型的“Content-Type”标头。以下是我的 Angular 应用程序配置:-

var app = angular.module("edit_modules", []);

app.config(function($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
});

这是我的补丁方法:-

$http.patch(url, data, {
    headers: {'Content-Type': 'application/json; charset=utf-8' }
}).then(successCallback, errorCallback);
function successCallback(response){
    console.log("Success");
    console.log(response);
};
function errorCallback(error){
    alert("Error Uploading!");
    console.log(error);
};

当我{'Content-Type': 'application/json; charset=utf-8' }通过标题时,我收到以下错误:-

"The submitted data was not a file. Check the encoding type on the form."
Status :- 400

由于它的内容类型是 file 我使用了以下 header {'Content-Type': 'multipart/form-data; charset=utf-8'}。但后来我得到了这个错误: -

Multipart form parse error - Invalid boundary in multipart: None
Status :- 400

正如此处链接中所建议的那样,我也尝试了以下标头{'Content-Type': undefined}但这也没有解决我的问题,并且出现以下错误:-

Unsupported media type "text/plain;charset=UTF-8" in request. 
Status :- 415

但是,当我尝试使用简单的文本字段时,PATCH 方法与提供的标题一起使用 {'Content-Type': 'application/json; 字符集=utf-8' }。我不确定问题出在哪里。我什至试图查看控制台,了解哪些数据被设置为要修补

data = {
    "video": element.files[0]
};
console.log(data);

这是我在控制台上得到的:-

{video: File(99861)}video: File(99861) {name: "Capture2.PNG", lastModified: 1517491665223, lastModifiedDate: Thu Feb 01 2018 18:57:45 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 99861, …}

任何帮助深表感谢。

标签: angularjsdjango

解决方案


参考这里的答案,我发现您需要附加要使用 FormData 发送的文件对象。此外,您还需要 config 中的附加标头transformRequest: angular.identity,。这是对我有用的成功的 PATCH 方法。

        var fd = new FormData();
        fd.append('video', element.files[0]);
        $http.patch(url, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(successCallback, errorCallback);
        function successCallback(response){
            console.log("Success");
            console.log(response);
        };
        function errorCallback(error){
            alert("Error Uploading!");
            console.log(error);
        };

第二行'video'是 REST API Endpoint 的变量,我的文件将在其中存储。为了避免错误

Multipart form parse error - Invalid boundary in multipart: None

我已经离开了headers: {'Content-Type': undefined}


推荐阅读