纹理上传的以下代码在
angularjs 1.2.26中工作,但在我将Web应用程序升级到1.3.0时停止工作.
<input file-model="file" name="file" type="file">
fileModel指令
app.directive('fileModel',[ '$parse',function($parse) { return { restrict : 'A',link : function(scope,element,attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change',function() { scope.$apply(function() { modelSetter(scope,element[0].files[0]); }); }); scope.$on("reset",function() { element.val(null); }); } }; } ]);
上传功能 – 在1.2.26中选择“multipart / form-data”,因为Content-Type不起作用.但是使用“未定义”作为内容类型角度会做某种使它工作的魔法.
var upload = function(textureUploadUrl) { var formData = new FormData(); formData.append('name',$scope.name); formData.append('file',$scope.file); $http.post(textureUploadUrl,formData,{ transformRequest : angular.identity,headers : { 'Content-Type' : undefined } }).success(function(uploadedTexture) { console.log(uploadedTexture); // further processing of uploadedTexture }); }
错误:
SyntaxError: Unexpected token h at Object.parse (native) at fromJson (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:1104:14) at defaultHttpResponseTransform (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:8572:18) at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:8517:12 at forEach (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:335:20) at transformData (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:8516:3) at transformResponse (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:9224:23) at processQueue (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:12914:27) at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:12930:27 at Scope.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js:14123:28)
有谁知道如何在新版本中使用它?
UPDATE
我已经把问题缩小了一点.它不适用于1.3.0-rc.5,但使用之前的版本(rc.4)它确实有效.所以,我目前正试图弄清楚哪些更改会导致我的问题.这是changelog.
问题出在我服务器端纹理上传请求的响应头中.为了构建我的应用程序,我使用了Spring MVC并且有一个像这样的请求映射,但没有产生规范:
@RequestMapping(value = "/uploadUrl",method = RequestMethod.POST,produces = "text/plain; charset=utf-8") @ResponseBody public String textureUploadPOST(HttpServletRequest req) { // upload texture and create serveUrl for the texture return serveUrl; }
因此,如果不将text / plain指定为Content-Type,Spring会自动将application / json用作Content-Type.这导致angular.js从1.3.0-rc.5(change)开始调用JSON.parse.我的纹理上传返回一个指向图像所在位置的URL.因为这是一个普通的字符串,所以它导致了所描述的错误消息.所以,不要忘记在服务器响应中指定正确的内容类型:-)