.NET mvc文件上传 常用方法


   最近在写手机端接口文件上传时,需要将写好的接口进行测试,写了个测试例子。主要功能是通过Ajax提交上传文件,后台将文件转为二进制 后,返回给前台,再调用另一个WEBAPI接口。网上查询了一些方法,在此感谢善于总结并把知识共享的人!     
  前台代码:

    
    文件上传测试
    
    
    
  


    
       @using (Html.BeginForm("UploadFile", "FileTest", FormMethod.Post, new { enctype = "multipart/form-data", id = "formFileUpload" }))     {                     }    
后台获取方法:
       public string  UploadFile()
        {


            HttpPostedFileBase hpf = Request.Files["fileUpload"]; //主要是这个地方获取到值就没问题了
            string fileName = hpf.FileName;
            string basePath = "/Temp/" + Guid.NewGuid().ToString() + "/";
            if (!Directory.Exists(Server.MapPath(basePath)))
                Directory.CreateDirectory(Server.MapPath(basePath));
            string fullPath = basePath + fileName;
            hpf.SaveAs(Server.MapPath(fullPath));
            string binaryString = MyCommon.FileToBinary(Server.MapPath(fullPath));
            FileModel model = new FileModel();
            model.EventId = "1";
            model.FileData = binaryString;
            model.FileName = fileName;
            model.FileExtension = fileName.Substring(fileName.LastIndexOf("."));
            model.Flag = 0;
            return JsonHelper.JsonSerializerToString(model);
        }


你可能感兴趣的:(Web前端)