Search code examples
jqueryasp.netasp.net-mvcasp.net-mvc-4jquery-file-upload

How to save file to mapped path apicontroller asp .net mvc4


So i am working on a project and am uploading a file with a progress bar. I have the progress bar working. My file comes in in segments to my controller and I need to save it to the server. Here is my Code for the apicontroller

namespace MvcMovie.Controllers.WebApi
{
public class UploadController : ApiController
{
    // Enable both Get and Post so that our jquery call can send data, and get a status
    [HttpGet]
    [HttpPost]
    public HttpResponseMessage Upload()
    {
        // Get a reference to the file that our jQuery sent.  Even with multiple files, they will all be their own request and be the 0 index
        HttpPostedFile file = HttpContext.Current.Request.Files[0];
        // do something with the file in this space 
        // {....}
        // end of file doing

        var filelenght = file.ContentLength;
        // Now we need to wire up a response so that the calling script understands what happened
        HttpContext.Current.Response.ContentType = "text/plain";
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var result = new { name = file.FileName };

        HttpContext.Current.Response.Write(serializer.Serialize(result));
        HttpContext.Current.Response.StatusCode = 200;

        // For compatibility with IE's "done" event we need to return a result as well as setting the context.response
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

}
}

But I am unsure how to save the file onto the server as it is coming in segments. On another project I did i used a normal controller and just used this:

    [Authorize]
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        var username = WebSecurity.CurrentUserName;

        if (file.ContentLength > 0)
        {

            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads/" + username), fileName);
            file.SaveAs(path);
        }

        return RedirectToAction("Index");
    }

But when i try implementing that code in my apicontroller Server.MapPath doesn't work. So I guess my question has 2 parts how do you save an uploaded file in a apiwebcontroller and how to save it when it is coming in segments?

Here is the javascript in my view of it if you want to look at it:

    $(function () {
        $('#fileupload').fileupload({
            dataType: "json",
            url: "/api/upload",
            limitConcurrentUploads: 1,
            sequentialUploads: true,
            progressInterval: 100,
            maxChunkSize: 10000,
            add: function (e, data) {
                $('#filelistholder').removeClass('hide');
                data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
                $('</div><div class="progress"><div class="bar" style="width:0%"></div></div>').appendTo(data.context);
                $('#btnUploadAll').click(function () {
                    data.submit();
                });
            },
            done: function (e, data) {
                data.context.text(data.files[0].name + '... Completed');
                $('</div><div class="progress"><div class="bar" style="width:100%"></div></div>').appendTo(data.context);
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#overallbar').css('width', progress + '%');
            },
            progress: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                data.context.find('.bar').css('width', progress + '%');
            }
        });
    });

Solution

  •         if (File.Exists(HttpContext.Current.Server.MapPath("~/App_Data/uploads/test/" + file.FileName)))
            {
                Stream input = file.InputStream;
                FileStream output = new FileStream(HttpContext.Current.Server.MapPath("~/App_Data/uploads/test/" + file.FileName), FileMode.Append);
                byte[] buffer = new byte[8 * 1024];
                int len;
                while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, len);
                }
                input.Close();
                output.Close();
            }
            else
            {
                file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/uploads/test/" + file.FileName));
            }
    

    So this is what i found that ended up working. When you are using and API controller to be able to map paths to the server you have to use. HttpContext.Current.Server.MapPath. Then all i had to do was create a file and append the file streams to it.