本文是用angularjs框架和$resource组件实现的,不过原理都是大同小异
注意重点: 设置请求的Content-Type头为undefined.
Angularjs 对于post和put请求,默认的Content-Type是application/json,w我们需要改变它的值. 通过设置Content-Type为undefined,浏览器会设置Content-Type为multipart/form-data,并且会自动填充正确的分界(boundary).
手动设定Content-Type为multipart/form-data,会导致请求的分界参数填充失败.
可以参考这个链接
http://www.jb51.cc/article/p-umvewndx-qu.html
html
<!--添加图片--> <div style=@H_502_20@"margin-top: 2rem;"> <div style=@H_502_20@"padding: 1rem 0;"><p>添加图片</p></div> <div style=@H_502_20@"display: flex; justify-content: flex-start; align-items: flex-start; flex-wrap: wrap; height: 14rem;"> <div class=@H_502_20@"images_upload" ng-repeat=@H_502_20@"image in uploadedImages track by $index" ng-click=@H_502_20@"removeImage(image)" style=@H_502_20@"background-image: url({{image}}@H_502_20@); "> </div> <div class=@H_502_20@"images_upload" onclick=@H_502_20@"document.getElementById('uploadImage').click()" ng-if=@H_502_20@"uploadedImages.length< 8" style=@H_502_20@"background-image: url(img/orders/jh@2x.png); background-size: inherit;"> </div> <input id=@H_502_20@"uploadImage" type=@H_502_20@"file" accept=@H_502_20@"image/*" multiple=@H_502_20@"true" style=@H_502_20@"display: none;"> </div> </div>
js_controller
var isUploading = false;
//选取图片绑定时事件
var uploadedButton = document.getElementById('uploadImage');
uploadedButton.onchange = function() {
//发请求
isUploading = true;
var formData = new FormData();
for(var index=0; index<uploadedButton.files.length; index++)
{
if (index+$scope.uploadedImages.length >= 8)
{
break;
}
formData.append('file',uploadedButton.files[index]);
}
//接口上传
buyerOrderService.uploadPictures(formData).then(
function(data) {
isUploading = false;
utilsService.console_info(data,'图片返回数据:');
if (!data || !data instanceof Array)
{
utilsService.console_error(data,'图片返回数据不规格;');
return;
}
//页面展示
for(var index=0; index<data.length; index++)
{
$scope.uploadedImages.push(data[index].data);
}
},function(error) {
isUploading = false;
utilsService.alert({template: '<a>图片上传失败,请稍后尝试</a>'})
});
};
//删除图片
$scope.removeImage = function(imageUrl) {
$scope.uploadedImages.splice($scope.uploadedImages.indexOf(imageUrl),1);
};
js_service
//resource的配置:
uploadPictures: {
url: requestUrl + '/upload/batch.do',/*/upload.do*/
isArray: true,method: 'POST',//这个很重要,必须加上
headers: {'Content-Type': undefined}
}
/** * 上传图片 */
service.uploadPictures = function(params)
{
return resource.uploadPictures(params).$promise;
};