我的目标:在我的AngularJS应用程序中向api提交一些表单数据(消息,类别,照片)。表单提交时,必须先将文件POST到服务器。成功的POST将返回带有令牌的对象。然后,该令牌将与其余的表单数据一起传递到另一个端点。
我的问题:我根本无法将文件发送到api!我被困在哪里,我错了。任何人都可以给予的任何建议将不胜感激。
HTML:我的表单使用ngSubmit来调用函数。
<form name="submitAnIdeaForm" data-ng-submit="functions.submitForm(submitAnIdeaForm)" novalidate>
<div class="form-top">
<div class="header">
<img data-ng-src="{{facebook.data.profile_picture.url}}" />
<h1>I'd like to see a story about...</h1>
</div>
<textarea
name="msg"
placeholder="*Tell us about your idea"
data-ng-model="form.msg"
data-ng-class="{ 'error' : submitAnIdeaForm.msg.$invalid && submitAnIdeaForm.submitted}"
required>
</textarea>
<div id="select-wrap">
<label for="idea-select">Select a Category <i class="icon-chevron-down"></i></label>
<select
id="idea-select"
name="category"
data-ng-model="form.category"
required>
<option value="">Select A Category</option>
<option data-ng-repeat="cat in categories" value="{{cat.id}}">{{cat.name}}</option>
</select>
<p class="error" data-ng-show="submitAnIdeaForm.category.$invalid && submitAnIdeaForm.submitted">*Please select a category</p>
</div>
<input
type="file"
name="photo"
data-ng-model="form.photo"
valid-file
required
/>
<p class="error" data-ng-show="submitAnIdeaForm.photo.$invalid && submitAnIdeaForm.submitted">*Please choose a photo</p>
</div>
<div class="submit">
<button type="submit">Submit</button>
</div>
</form>
控制器JS:form是原始对象angular给你
// Form Validation / Submit
submitForm: function(form) {
if(form.$valid){
// Post the idea
Api.postIdea(form);
// Send the user to the thank you page
$location.path('/thank-you');
}
}
服务JS:上面的代码调用postIdea(),用于发布之后的所有表单数据。所以首先它调用这个方法postFile,这是我遇到麻烦的方法。
postFile: function(form) {
var fd = new FormData();
fd.append('file', form.photo);
$http({
method: 'POST',
url: this.api_base + '/upload',
data: fd,
headers: {
'Content-Type': "multipart/form-data"
},
transformRequest: angular.identity,
withCredentials: true
}).success(function(data, status, headers, config){
if(data.success){
console.log("Success:", data, status, headers, config);
} else {
console.log("Error:", data, status, headers, config);
}
});
}
Api回复
Error: Disallowed Key Characters. 200