-1

I am uploading a file using via a view linked to a controller however after the upload is uploaded the application is either trying to refresh or redirect and I need to prevent this. May you please point me in the right direction to avoid redirection and refresh? I have done a bit of reading and I suspect that this line action="/api/BulkUpload">might be causing the problem.

My Controller

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);
         }
      }





   }
}

MY 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>
tereško
  • 58,060
  • 25
  • 98
  • 150
Zidane
  • 1,696
  • 3
  • 21
  • 35

2 Answers2

4

You're correct. When you submit the form, the file is sent to the controller via a HTTP POST request and the page is either, necessarily, refreshed or redirected. If you don't want to the page to refresh or redirect, then you'll have to use AJAX to post the file to the controller.

From a Mozilla Developer document on HTTP requests,

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

From these notes on Web Programming from Nanyang Technological University,

[The] POST request method is used to "post" additional data up to the server (e.g., submitting HTML form data or uploading a file). Issuing an HTTP URL from the browser always triggers a GET request. To trigger a POST request, you can use an HTML form with attribute method="post" or write your own network program. For submitting HTML form data, POST request is the same as the GET request except that the URL-encoded query string is sent in the request body, rather than appended behind the request-URI.

So, you can see that since you're posting a file to the server using a standard HTTP request, it is necessarily going to refresh or redirect in some way.

To avoid this, you can use jQuery to asynchronously post the file to the server without refreshing the page. There are plenty of articles on how to do this. I suggest you give it a try and post another question if you get stuck.

Community
  • 1
  • 1
Jack
  • 1,453
  • 1
  • 15
  • 35
0

Thanks so much for the help it guided me in the right direction. I eventually got my answer from this [How to submit html form without redirection? . The Iframe approach is the simplest approach it is a temporary fix seeing as some articles are saying that although it is still supported by most modern browsers it has been deprecated.

Zidane
  • 1,696
  • 3
  • 21
  • 35