【问题标题】:How to upload image in ASP.NET MVC 4 using ajax or any other technique without postback?如何在没有回发的情况下使用 ajax 或任何其他技术在 ASP.NET MVC 4 中上传图像?
【发布时间】:2013-01-12 14:28:42
【问题描述】:

我正在 MVC 4 中开发一个网站,用户在其中填写一些信息并将其保存以供上传。 除图像外的所有信息都使用 Javascript、Json 和 Ajax 保存在服务器上,如下所示:

$.ajax({
                    url: action,
                    type: "POST",
                    data: JSON.stringify(PostViewModel),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    beforeSend: function () {            
                    },
                    success: function (data) {
                    try{
                        alert('success');
                    }catch(err){alert(' Error: '+err);}

                    },
                    complete: function () {
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error occured");
                    }
            });

但是现在我也需要上传他的图片,但我找不到任何可以使用这种方法的方法,或者没有任何不回发的方法。

我知道将 FileUpload 控件放在 Form 标记中,然后按下提交按钮,我可以获得如下所示的图像文件:

 HttpPostedFileBase photo = Request.Files["photo"];
        if (photo != null)
        {
            Session["ImgPath"] = "~/Content/PostImages/" + photo.FileName;
            string path = Server.MapPath("~/Content/PostImages/");
            photo.SaveAs(path + photo.FileName);
        }

但是对于这种方法,我将不得不改变我不能保存内容的方法(使用 Javascript、Json 和 Ajax)。

请帮忙

谢谢。

【问题讨论】:

    标签: c#-4.0 file-upload asp.net-mvc-4


    【解决方案1】:

    HTML 代码

    <input type="file"  id="uploadEditorImage"  />
    

    Javascript 代码

    $("#uploadEditorImage").change(function () {
        var data = new FormData();
        var files = $("#uploadEditorImage").get(0).files;
        if (files.length > 0) {
            data.append("HelpSectionImages", files[0]);
        }
        $.ajax({
            url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
            type:"POST",
            processData: false,
            contentType: false,
            data: data,
            success: function (response) {
               //code after success
    
            },
            error: function (er) {
                alert(er);
            }
    
        });
    });
    

    MVC 控制器中的代码

    if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
            {
                var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
            }
    

    【讨论】:

    • 控制器动作应该传递什么参数?
    • 我应该使用@if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) { var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"]; pic.SaveAs("/" + pic.FileName); } 吗?
    • 我在想 - 为什么 Ajax.BeginForm 不能在这里工作,但纯 JS 是 :) 仍然 - 很好的答案
    【解决方案2】:

    有两种方式可以异步发布文件(图片) 如果您的目标浏览器支持文件 api,您可以使用以下内容: HTML:

    <input type="file" name="etlfileToUpload" id="etlfileToUpload"  />
    

    JavaScript

    // Call this function on upload button click after user has selected the file 
    function UploadFile() {
        var file = document.getElementById('etlfileToUpload').files[0];
        var fileName = file.name;    
        var fd = new FormData();    
        fd.append("fileData", file);    
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
        xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
        xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
        xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
        xhr.open("POST", "{URL}", true); 
        xhr.send(fd);
    }
    
    
    function UploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            $("#uploading").text(percentComplete + "% ");        
        }
    }
    
    function UploadComplete(evt) {
        if (evt.target.status == 200)
            alert(evt.target.responseText);
        else {
            alert("Error Uploading File");
        }
    }
    
    function UploadFailed(evt) {    
        alert("There was an error attempting to upload the file.");
    }
    
    function UploadCanceled(evt) {    
        alert("The upload has been canceled by the user or the browser dropped the connection.");
    }
    

    或者你可以使用像uploadify这样的swf工具

    【讨论】:

    • 感谢您发布此消息!
    • 今天过来发帖,一切都还好,但是UploadProgress有一个jquery,在javascript上添加了一点苦涩:-)
    【解决方案3】:

    我个人不喜欢使用除 java script、css 或 html 之外的任何第三方工具。我将采用 UmairP 展示的第一种方法。但是,如果您想节省自己编写大量代码的时间。这是一个很好的 jquery plugin

    还有一个demo 用于带有这个插件的asp.net mvc。

    请看一看。让我知道是否需要任何进一步的信息。

    【讨论】:

      【解决方案4】:

      试试这个对我有用

         <input type="file" name="Upload" id="Upload" />
      
      $('#Upload').change(function () {
          debugger;
          var file = document.getElementById('Upload').files[0];
          var fileName = file.name;
          var fd = new FormData();
          fd.append("fileData", file);
          fd.append("key", '@Model.Id');
      
          var xhr = new XMLHttpRequest();
          xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
          xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
          xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
          xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
          xhr.open("POST", "/ImageHandler.ashx", true);
          xhr.send(fd);
      });
      
      
      function UploadProgress(evt) {
          if (evt.lengthComputable) {
              var percentComplete = Math.round(evt.loaded * 100 / evt.total);
              //$("#uploading").text(percentComplete + "% ");
          }
      }
      
      function UploadComplete(evt) {
          //if (evt.target.status == 200)
              //alert(evt.target.responseText);
          //else {
          //   // alert("Error Uploading File");
          //}
      }
      
      function UploadFailed(evt) {
         // alert("There was an error attempting to upload the file.");
      }
      
      function UploadCanceled(evt) {
          //alert("The upload has been canceled by the user or the browser dropped the connection.");
      }
      

      处理程序:

      public class ImageHandler : IHttpHandler
      {
          public void ProcessRequest(HttpContext context)
          {
              //context.Response.ContentType = "text/plain";
              //context.Response.Write("Hello World");]
      
      
      
              string filePath = Constants.ImageFolderPath;
      
              //write your handler implementation here.
              if (context.Request.Files.Count <= 0)
              {
                  context.Response.Write("No file uploaded");
              }
              else
              {
                  for (int i = 0; i < context.Request.Files.Count; ++i)
                  {
                      HttpPostedFile file = context.Request.Files[i];
                      if (context.Request.Form != null)
                      {
                          string imageid = context.Request.Form.ToString();
                          imageid = imageid.Substring(imageid.IndexOf('=') + 1);
      
                          if (file != null)
                          {
                              string ext = file.FileName.Substring(file.FileName.IndexOf('.'));
                              if (ext.ToLower().Contains("gif") || ext.ToLower().Contains("jpg") || ext.ToLower().Contains("jpeg") || ext.ToLower().Contains("png"))
                              {
      
                                  byte[] data;
                                  using (Stream inputStream = file.InputStream)
                                  {
                                      MemoryStream memoryStream = inputStream as MemoryStream;
                                      if (memoryStream == null)
                                      {
                                          memoryStream = new MemoryStream();
                                          inputStream.CopyTo(memoryStream);
                                      }
                                      data = memoryStream.ToArray();
                                      File.WriteAllBytes(Constants.ImageFolderPath + imageid + ".jpg", (byte[])data);
                                      //club.club_image = Convert.ToBase64String(data);
                                  }
                              }
                          }
                      }
                      else
                      {
      
                      }
      
                      //file.SaveAs(context.Server.MapPath(filePath + file.FileName));
                      context.Response.Write("File uploaded");
                  }
              }
          }
      
          public bool IsReusable
          {
              get
              {
                  return false;
              }
          }
      }
      

      【讨论】:

        【解决方案5】:
        $(document).ready(function(){
           var status = $('#status');
        
                $('#frmUpload').ajaxForm({
                    beforeSend: function () {
                        if ($("#file").val() != "") {                   
                            $("#progressDiv").show();                    
                        }
                        status.empty();
                    },
                    success: function () {
                        showTemplateManager();
                    },
                    complete: function (xhr) {
                        if ($("#file").val() != "") {
                            var millisecondsToWait = 500;
                            setTimeout(function () {                       
                             $("#progressDiv").hide();
                            }, millisecondsToWait);
                        }
                        status.html(xhr.responseText);
                    }
                });
        });
        

        【讨论】:

          【解决方案6】:

          我也遇到了类似的问题,在被卡住了很多天之后,这个链接终于帮助了我

          Jquery Uploadiy with Progress Bar to be Used with MVC

          这就是我的管理方式

          public JsonResult Upload(HttpPostedFileBase file)
          {
              if (Session["myAL"] == null)
              {
                  al = new ArrayList();
              }
              else
                  al = (ArrayList)Session["myAL"];
          
              var uploadFile = file;
          
                  if (uploadFile != null && uploadFile.ContentLength > 0)
                  {
                      string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Uploads"),
                                                         Path.GetFileName(uploadFile.FileName));                    
                      al.Add(filePath);
                      Session["myAL"] = al;
                      uploadFile.SaveAs(filePath);
                  }
          
              var percentage = default(float);
          
              if (_totalCount > 0)
              {
                  _uploadCount += 1;
                  percentage = (_uploadCount / _totalCount) * 100;
              }
          
              return Json(new
              {
                  Percentage = percentage
              });
          }
          

          How to Implement Attach More Files in MVC and jquery for FileUploading

          【讨论】:

            【解决方案7】:
            <input type="file" name="file" id="file" style="width: 100%;"onchange="readURL(this);" />
            
             if (file != null && file.ContentLength > 0)
                            {
                                string filename = Path.GetFileName(file.FileName);
                                string imgpath = Path.Combine(Server.MapPath("~/Img/"), filename);
                                file.SaveAs(imgpath);
                                student.photo = imgpath;
                            }
            
            function readURL(input)
                {
                    if (input.files && input.files[0]) {
                        var reader = new FileReader();
            
                        reader.onload = function (e) {
                            $('#imgUser')
                                .attr('src', e.target.result)
                                .width(150)
                                .height(200);
                        };
            
                        reader.readAsDataURL(input.files[0]);
                    }
                }
            

            【讨论】:

            • 请补充说明
            猜你喜欢
            • 2012-12-12
            • 2017-03-10
            • 1970-01-01
            • 2010-10-06
            • 2021-08-14
            • 1970-01-01
            • 2018-08-28
            • 2015-12-04
            • 1970-01-01
            相关资源
            最近更新 更多