我仍然对上传文件的不同方法感到困惑.后端服务器不受我的控制,但我可以使用Swagger页面或Postman上传文件.这意味着服务器运行正常.但是当我使用AngularJS进行上传时,它不起作用.
以下是使用Postman进行测试的方法.我只是使用表单数据:
请注意,请求标头将Content-Type作为multipart / form-data.但Request Payload的文件名和Content-Type为image / png.
这是我的代码:
$http({ method: 'POST',url: ApiUrlFull + 'Job/Item?smartTermId=0&name=aaa1&quantity=1&ApiKey=ABC',headers: { 'Content-Type': undefined },transformRequest: function(data) { var fd = new FormData(); fd.append('file',params.imageData); return fd; } })
我的代码也发送类似的URL参数(所以我们可以忽略导致问题).但请求有效负载是base64,它看起来不同,因为它缺少文件名字段.
我对后端没有控制权,它是用.NET编写的.
所以我想我的问题是:使用Angular($http或$resource),如何修改请求,以便我发送正确的Request Payload,就像Postman一样?我无法弄清楚如何对此进行逆向工程.
我试过这个https://github.com/danialfarid/ng-file-upload,它实际上在POST之前先做了OPTIONS请求(假设CORS问题).但服务器为OPTIONS提供了405错误.
解决方法
您可以使用以下内容:
<input type="file" name="file" onchange="uploadFile(this.files)"/>
在你的代码中:
$scope.uploadFile = function(files) { var fd = new FormData(); //Take the first selected file fd.append("file",files[0]); var uploadUrl = ApiUrlFull + 'Job/Item?smartTermId=0&name=aaa1&quantity=1&ApiKey=ABC'; $http.post(uploadUrl,fd,{ withCredentials: true,headers: {'Content-Type': undefined },transformRequest: angular.identity }).success( ...all right!... ).error( ..damn!... ); };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。