File Upload ASP.NET MVC 3.0

后端 未结 21 994
无人共我
无人共我 2020-11-22 01:09

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to

21条回答
  •  执念已碎
    2020-11-22 01:42

    file upload using formdata

    .cshtml file

         var files = $("#file").get(0).files;
         if (files.length > 0) {
                    data.append("filekey", files[0]);}
    
    
       $.ajax({
                url: '@Url.Action("ActionName", "ControllerName")', type: "POST", processData: false,
                data: data, dataType: 'json',
                contentType: false,
                success: function (data) {
                    var response=data.JsonData;               
                },
                error: function (er) { }
    
            });
    

    Server side code

    if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
                    {
                        var pic = System.Web.HttpContext.Current.Request.Files["filekey"];
                        HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
                        var fileName = Path.GetFileName(filebase.FileName);
    
    
                        string fileExtension = System.IO.Path.GetExtension(fileName);
    
                        if (fileExtension == ".xls" || fileExtension == ".xlsx")
                        {
                            string FileName = Guid.NewGuid().GetHashCode().ToString("x");
                            string dirLocation = Server.MapPath("~/Content/PacketExcel/");
                            if (!Directory.Exists(dirLocation))
                            {
                                Directory.CreateDirectory(dirLocation);
                            }
                            string fileLocation = Server.MapPath("~/Content/PacketExcel/") + FileName + fileExtension;
                            filebase.SaveAs(fileLocation);
    }
    }
    

提交回复
热议问题