【问题标题】:How to do File Upload Without Page Refresh or redirect in ASP.NET MVC如何在没有页面刷新或重定向的情况下在 ASP.NET MVC 中进行文件上传
【发布时间】:2019-04-03 13:11:11
【问题描述】:

我正在使用链接到控制器的视图上传文件,但是在上传上传后,应用程序要么尝试刷新或重定向,我需要防止这种情况发生。能否请您指出正确的方向以避免重定向和刷新?我做了一些阅读,我怀疑这条线action="/api/BulkUpload">可能是导致问题的原因。

我的控制器

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Repositories.BulkUpload;
using Repositories.Interfaces.BulkUpload;

namespace SimSentinel.Controllers
{
    //[Authorize]
   public class BulkUploadController : ApiController
   {
      private readonly IBulkUploadRepository _bulkUploadRepository;
      public async Task<HttpResponseMessage> PostFile()
      {
         // Check if the request contains multipart/form-data.
         if (!Request.Content.IsMimeMultipartContent())
         {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
         }

         string root = HttpContext.Current.Server.MapPath("~/Files");
         var provider = new FormDataStreamer(root);

         try
         {
            StringBuilder sb = new StringBuilder(); // Holds the response body 



            // Read the form data and return an async task. 
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the form data. 
            foreach (var key in provider.FormData.AllKeys)
            {
               foreach (var val in provider.FormData.GetValues(key))
               {
                  sb.Append(string.Format("{0}: {1}\n", key, val));
               }
            }


            // This illustrates how to get the file names for uploaded files. 
            foreach (var file in provider.FileData)
            {
               FileInfo fileInfo = new FileInfo(file.LocalFileName);
               sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
            }
            return new HttpResponseMessage()
            {
               Content = new StringContent(sb.ToString())
            };
         }
         catch (System.Exception e)
         {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
         }

      }

      public class FormDataStreamer : MultipartFormDataStreamProvider
      {
         public FormDataStreamer(string rootPath) : base(rootPath) { }
         public FormDataStreamer(string rootPath, int bufferSize) : base(rootPath, bufferSize) { }
         public override string GetLocalFileName(HttpContentHeaders headers)
         {
            var srcFileName = headers.ContentDisposition.FileName.Replace("\"", "");
            return Guid.NewGuid() + Path.GetExtension(srcFileName);
         }
      }





   }
}

我的 HTML

 <form name="form1" method="post" enctype="multipart/form-data" action="/api/BulkUpload">
         <div>
            <label for="caption">Image Caption</label>
            <input name="caption" type="text" />
         </div>
         <div>
            <label for="image1">Image File</label>
            <input name="image1" type="file" />
         </div>
         <div>
            <input type="submit" value="ok" />
         </div>
      </form>

【问题讨论】:

    标签: asp.net-mvc forms file-upload httpresponse


    【解决方案1】:

    非常感谢它为我指引正确方向的帮助。我最终从这个 [How to submit html form without redirection? 中得到了答案。 Iframe 方法是最简单的方法,它是一种临时修复,正如一些文章所说,尽管大多数现代浏览器仍然支持它,但它已被弃用。

    【讨论】:

      【解决方案2】:

      你是对的。当您提交表单时,文件会通过 HTTP POST 请求发送到控制器,并且页面必须刷新或重定向。如果您不希望页面刷新或重定向,则必须使用 AJAX 将文件发布到控制器。

      来自Mozilla Developer document on HTTP requests

      GET 方法请求指定资源的表示。 使用 GET 的请求应该只检索数据。

      POST方法用于提交一个实体到指定的 资源,通常会导致状态变化或对资源产生副作用 服务器。

      来自Web Programming from Nanyang Technological University 上的这些注释,

      [The] POST 请求方法用于向服务器“发布”附加数据 (例如,提交 HTML 表单数据或上传文件)。发出 HTTP 来自浏览器的 URL 总是会触发 GET 请求。触发 POST 请求,您可以使用带有属性 method="post" 的 HTML 表单或 编写自己的网络程序。对于提交 HTML 表单数据,POST 请求与 GET 请求相同,只是 URL 编码 查询字符串在请求正文中发送,而不是附加在后面 请求 URI。

      因此,您可以看到,由于您使用标准 HTTP 请求将文件发布到服务器,它必然会以某种方式刷新或重定向。

      为避免这种情况,您可以使用 jQuery 将文件异步发布到服务器而不刷新页面。有很多关于如何做到这一点的文章。我建议您尝试一下,如果遇到困难,请发布另一个问题。

      【讨论】:

        猜你喜欢
        • 2011-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 2020-03-22
        相关资源
        最近更新 更多