1

Below I have the relevant code parts for my AJAX image upload for my MVC4 ASP.Net application. However when I click on the upload link it simply appends an # to the end of my URL link so http://localhost:10991/StoreManager/Create# and goes to the top of the page.

There are no errors I can see appearing in the Debugger or console window.

I have used the code from here

http://powerdotnetcore.com/asp-net-mvc/asp-net-mvc-simple-ajax-file-upload-using-jquery

_PartialView

   @model SwitchClothing.Models.Image

   <script src="~/Scripts/jquery-2.1.0.min.js"></script>
   <script src="~/Scripts/jquery-ui-1.10.4.js"></script>
   <script src="~/Scripts/jquery.validate.min.js"></script>
   <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
   <script src="~/Scripts/FileUpload/jquery.fileupload.js"></script>
   <script src="~/Scripts/FileUpload/jquery.fileupload-ui.js"></script>
   <script src="~/Scripts/FileUpload/jquery.iframe-transport.js"></script>
   <script src="~/Scripts/upload.js"></script>


   <div class="well">
       <div>
           <h1>Upload by click</h1>
       </div>
       <div>@Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file" }) &nbsp;<a href="#" id="hl-start-upload">Start upload</a> </div>
   </div>

Upload.js

    var jqXHRData;

$(document).ready(function () {

    initSimpleFileUpload();

    $("#hl-start-upload").on('click', function () {
        if (jqXHRData) {
            jqXHRData.submit();
        }
        return false;
    });

});

function initSimpleFileUpload() {
    'use strict';

    $('#fu-my-simple-upload').fileupload({
        url: '/File/UploadFile',
        dataType: 'json',
        add: function (e, data) {
            jqXHRData = data
        },
        done: function (event, data) {
            if (data.result.isUploaded) {

            }
            else {

            }
            alert(data.result.message);
        },
        fail: function (event, data) {
            if (data.files[0].error) {
                alert(data.files[0].error);
            }
        }
    });
}

Controller Action

[HttpPost]
        public virtual ActionResult UploadFile()
        {
            HttpPostedFileBase myFile = Request.Files["MyFile"];
            bool isUploaded = false;
            string message = "File upload failed";

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/Images");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                        isUploaded = true;
                        message = "File uploaded successfully!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("File upload failed: {0}", ex.Message);
                    }
                }
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }

        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    /*TODO: You must process this exception.*/
                    result = false;
                }
            }
            return result;
        }

Rendering the partial view in the Create page of model view

@RenderPage("_Upload.cshtml")

1 Answer 1

1

If you want to do Upload functionality, I think you should put <input type='file' /> inside a html form. Because the Form will need enctype="multipart/form-data" attribute for uploading file.

<form id="ajaxUploadForm" action="/Import" method="post" enctype="multipart/form-data">
         <div class="entry-form">
                <div class="editor">
                    <div class="editor-label">
                        File:
                    </div>
                    <div class="editor-field">
                       <input id="import-file" type="file" name="file" />
                       <input type="submit" class="btn" value="Submit" />       
                    </div>
                    <div class="clear">
                    </div>
                </div>                      
          </div>   
</form>

Upload js could be:

 // Upload file and import
$("#ajaxUploadForm").ajaxForm({
    iframe: true,
    type: 'POST',
    dataType: "json",
    cache: false,
    timeout: 1200000,
    async: false,        
    success: function (result) {            
       // do something when successfully
    },
    error: function (xhr, textStatus, errorThrown) {
       // do something when error
    }
});

And Controller Action, it could be similar to your codes.

Cheers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.