如何在asp.mvc中使用ng-file-upload上传文件

时间:2015-08-19 15:09:14

标签: asp.net-mvc angularjs ng-file-upload

如何在asp.mvc中使用ng-file-upload上传文件?

我使用此代码在asp.mvc中使用ng-file-upload上传文件:

public class HomeController : Controller, IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            bool result;
            try
            {
                HttpPostedFile file = context.Request.Files[0];
                if (file.ContentLength > 0)
                {
                    string nameFile = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
                    var path = Path.Combine(Server.MapPath(Url.Content("~/Temp/")), nameFile);
                    file.SaveAs(path);    
                }
                result = true;
            }
            catch (Exception exception)
            {
                result = false;
            }
            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

脚本:

 $scope.$watch('file', function (file) {
    if (file&&!file.$error) {
        $scope.upload($scope.file);
    }
});
$scope.upload = function (file) {
    Upload.upload({
        url: getBaseUrl() + 'Home/ProcessRequest',
        file: file
    }).progress(function(evt) {
        $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + $scope.progressPercentage + '% ' + evt.config.file.name);
    }).success(function (data, status, headers, config) {
        console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
    }).error(function (data, status, headers, config) {
        console.log('error status: ' + status);
    });
};

错误:

POST http://localhost:1726/Home/ProcessRequest 500(内部服务器错误) 没有为此对象定义无参数构造函数。

编辑:

我正在使用此代码:

   public class HomeController : Controller
    {
        [HttpPost]
        [AllowUploadSpecialFilesOnly(".pdf,.doc,.docx,ppt,pptx,.mp3")]
        public JsonResult Resume(HttpPostedFileBase file)
        {
            bool result;
            try
            {
                if (file != null && file.ContentLength > 0 && file.FileName != null)
                {
                    string nameFile = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
                    var path = Path.Combine(Server.MapPath(Url.Content("~/Temp/")), nameFile);
                    file.SaveAs(path);
                }
                result = true;
            }
            catch (Exception exception)
            {
                result = false;
            }
            return Json(new
            {
                Result = result
            }, JsonRequestBehavior.AllowGet);
        }
     }

html:

<form class="form-horizontal text-center" role="form" name="upload_form" >
    <div class="form-group">
        <div class="btn btn-primary" ngf-pattern="'.pdf,.doc,.docx,ppt,pptx,.mp3,.apk'" ngf-select ng-model="file">Send</div>
    </div>
    <span class="progress" ng-show="file.progress >= 0">
        <div class="ng-binding" style="width:{{file.progress}}%" ng-bind="file.progress + '%'"></div>
    </span>
</form>

scropt:

  $scope.upload = function (file) {
                Upload.upload({
                    url: getBaseUrl() + 'Home/Resume',
                    file: file
                }).progress(function(evt) {
                    $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    console.log('progress: ' + $scope.progressPercentage + '% ' + evt.config.file.name);
                }).success(function (data, status, headers, config) {
                    console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
                }).error(function (data, status, headers, config) {
                    console.log('error status: ' + status);
                });
            };

这很好。但progressPercentage始终为100%,但文件正在上传

1 个答案:

答案 0 :(得分:0)

这里是主人https://github.com/danialfarid/ng-file-upload 并参阅教程http://jsfiddle.net/danialfarid/0mz6ff9o/135/

第0步 按照上面的教程步骤

第1步 index.cshtml中的modif url参数

url:'@ Url.Action(“UploadDocument”)',

file.upload = Upload.upload({
                  url: '@Url.Action("UploadDocument")',
                  data: {
                     File: file,
                     Description:'test'
                  }
               });

第2步 在c#Controller中创建 UploadDocument(UploadRq数据)

 public JsonResult UploadDocument(UploadRq data)
      {

         //your code
         //string filename = Path.GetFileName(data.File.FileName);     
         //data.File.SaveAs(Server.MapPath("~/DocumentUploaded/") + filename);
         return Json("Saved", JsonRequestBehavior.AllowGet);
      }

第3步 创建课程 UploadRq.cs

public class UploadRq
   {
      public HttpPostedFileBase File { get; set; }
      public string Description { get; set; }
   }