以下用于纹理上传的代码在angularjs 1.2.26中可用,但是在将Web应用程序升级到1.3.0时停止了工作。

HTML代码

<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将不起作用。但是使用“未定义”作为Content-Type angular会产生某种魔力,使它起作用。

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)


有谁知道如何在新版本中使用它?

更新

我已经将问题缩小了一点。它不适用于1.3.0-rc.5,但适用于先前版本(rc.4)。因此,我目前正在尝试找出导致我的问题的更改。这是changelog

最佳答案

问题出在服务器端我的纹理上传请求的响应标头中。为了构建我的应用程序,我使用了Spring MVC并具有类似的请求映射,但是没有produces规范:

@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。从1.3.0-rc.5(change)开始,这导致angular.js调用JSON.parse。我的纹理上传返回一个URL,该URL指向提供图像的位置。因为这是一个纯字符串,所以导致了所描述的错误消息。因此,不要忘记在服务器响应中指定正确的Content-Type :-)

07-24 09:44
查看更多