The following code is set in the angular project for some reasons:
// $locationProvider.html5Mode(true);
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for (name in obj) {
value = obj[name];
if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value instanceof Object) {
for (subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function (data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
As a result, files cannot be uploaded now, and even the simplest form submission does not work:
<form action="upload/url" name="form1" method="post" enctype="multipart/form-data">
<input id="file" name="file" type="file" accept="image/*">
<button type="submit" class="btn btn-primary btn-lg">提交</button>
</form>
Asking for help from all the experts, how can I upload pictures normally? Urgent, very urgent, the project has been delayed for one day... Thank you!
https://github.com/nervgh/ang... Take it, you’re welcome
The subject asked two questions: 1. Why did we set the header? 2. How to upload pictures
1. Why do you have to set the header? Add the header setting to the base level httpProvider
http://stackoverflow.com/ques...
Company programmers should refer to this question. Your company's back-end api interaction uses Content-Type: x-www-form-urlencoded, and angular uses Content-type: application/json. So the Content-type and serialization were changed. The subject can refer to it.
2. Upload pictures
The subject’s description is not very clear as to how this submission was initiated. But the problem is because the content-type of the file submission is set incorrectly. Provide a method to submit using FormData:
Your js code is to encode the data into
x-www-form-urlencoded
form. But there is no data binding in your html, which is definitely not possible! So I suspect that you haven't understood the use of angularjs at all.Also, you didn’t explain clearly how you posted the data. Who knows where your problem lies?
Come back after posting the complete code