Search code examples
javascriptjqueryasp.netajaxjquery-file-upload

Upload file with text using AJAX & ASP.NET


I am having trouble uploading a file and value from a textbox/textarea in a single AJAX post. The entire project was created with AJAX posts to send data and receive resulting html/data. This means every button is handled with javascript/jquery and not asp.net's default onClick. Searches online yield answers with file upload but none of them show or explain any way to pass other parameters/data along with it.

*EDIT - I am not receiving any specific errors or crash attempting this. I try to run the file upload code in the success of the note upload or vice versa. It doesn't seem to be able to run both even if I switch it to asynchronous. I am more trying to get ONE single AJAX post to send both the file and the note to be handled in one codebehind function.

*EDIT(due to duplicate flag) - This is ASP.NET, not php. Please fully read questions before jumping to duplicate/closed conclusions.

Below is code/example of what I have so far.

HTML :

<div id="Modal_New_Document" class="modal fade" role="dialog">
    <div class="modal-dialog Modal-Wrapper">
        <div class="modal-content">
            <div class="modal-header Modal-Header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3 class="modal-title">Upload New Document</h3>
            </div>
            <div class="modal-body Modal-Body">
                <table>
                    <tr>
                        <th>Document :</th>
                        <td>
                            <input type="file" id="FileUpload_Modal_Document" />
                        </td>
                    </tr>
                    <tr>
                        <th>Note :</th>
                        <td>
                            <textarea id="TextArea_Modal_Document_Note" style="width: 400px;"></textarea>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer Modal-Footer">
                <button type="button" class="btn btn-success" onclick="enterDocumentInfo()">Upload</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

This is the most important part. I prefer to upload using the $.Ajax such as the example below. I was able to get only the file upload to work with the submitDocument() Javascript :

function submitDocument()
{
    var fileUpload = $("#FileUpload_Modal_Document").get(0);
    var files = fileUpload.files;

    var data = new FormData();
    for (var i = 0; i < files.length; i++) {
        data.append(files[i].name, files[i]);
    }

    var options = {};
    options.url = "FileUploadHandler.ashx";
    options.type = "POST";
    options.data = data;
    options.contentType = false;
    options.processData = false;
    options.success = function (result) { alert("Gud"); };
    options.error = function (err) { alert(err.statusText); };
    $.ajax(options);    
}

$.ajax({
    type: "POST",
    url: "Lease_View.aspx/enterDocument",
    data: JSON.stringify({
        leaseID: leaseID,
        userID: userID,
        note: note
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function ()
    {
        // Gud
    },
    error: function ()
    {
        // Bad
    }
});

Codebehind FileUpload

public class FileUploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                // Upload code here
            }
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write("File(s) Uploaded Successfully!");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

WebMethod Codebehind

I prefer to be able to upload file through this instead of above.

[System.Web.Services.WebMethod]
    public static void enterDocument(string leaseID, string userID, string note)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
        SqlCommand cmd;
        cmd = new SqlCommand("INSERT INTO Lease_Documents " +
                    "(File_Name) " +
                    "VALUES " +
                    "(@File_Name)", conn);
        cmd.Parameters.AddWithValue("@File_Name", note);
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }

Solution

  • I figured it out. Basically how to pass additional parameters is using data.append(name, value) in the javascript. You can receive the value in the .ashx handler by using (HttpContext)context.Request.Form["name"]. Unfortunately it is using the handler instead of the webmethod, but at least it works.

    In Javascript

    var data = new FormData();
    for (var i = 0; i < files.length; i++) {
        data.append(files[i].name, files[i]);
    }
    data.append("Note", note);
    

    In Codebehind

    string note = context.Request.Form["Note"].ToString();