使用AngularJS上传文件

时间:2014-09-12 13:01:15

标签: ajax asp.net-mvc angularjs xmlhttprequest

我想以AJAX方式上传图片,并参考此Article

这样做

我做了什么:

控制器:

$scope.uploadImage = function () {
    var result;
    var formdata = new FormData();
    var fileInput = document.getElementById('fileInput');
    for (var i = 0; i < fileInput.files.length; i++) {
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Common/Image_upload?imageType=' + $scope.imageType);
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
};

查看:

<form id="uploader" ng-submit="uploadImage()">
    <input id="fileInput" type="file">
    <input type="submit" value="Upload file" />
</form>

MVC控制器:

 [HttpPost]
 public JsonResult Image_upload(string imageType)
 {
     ....
     success = ProductImage_insert(Image);
     message = success ? "Image uploaded successfully!" : "Image was not uploaded!";
     return Json(message, JsonRequestBehavior.AllowGet);
 }

要求: 我需要在控制器中捕获这个JSON响应,我该怎么办?

提前致谢。

1 个答案:

答案 0 :(得分:1)

你可以有角度地做到这一点:

$scope.uploadImage = function () {
        var fileInput = document.getElementById('fileInput');
        var messageHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' };
        messageHeaders['X-File-Name'] = encodeURI(fileInput.files[0].name);
        messageHeaders['X-File-Type'] = encodeURI(fileInput.files[0].type);
        var fileData = fileInput.files[0];

        $http({
            url: '/Common/Image_upload',
            method: "POST",
            data: fileData,
            headers: messageHeaders
        }).success(function (data, status, headers, config) {
            // do what you want with the response
        });
    }
服务器上的

读取Request.InputStream以获取文件内容

[HttpPost]
public virtual ActionResult Image_upload(productType)
{
    var xfileName = HttpUtility.UrlDecode(Request.Headers["X-File-Name"]);
    var xfileType = HttpUtility.UrlDecode(Request.Headers["X-File-Type"]);
    var inputStream = Request.InputStream;
    var fileLenght = (int)inputStream.Length;
    var bytes = new byte[fileLenght];
    Request.InputStream.Read(bytes, 0, fileLenght);

    System.IO.File.WriteAllBytes(Server.MapPath("/MyFiles/" + xfileName), bytes);

    // return status code 200 or any other data
    return new HttpStatusCodeResult(200);
}