1

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();
    }
  • Are you getting an error? Where does it breakdown? – Glenn Ferrie May 15 '18 at 00:42
  • @GlennFerrie No errors at it's current state. If I try to run it as a two step submit, as in upload first and then append note, I cannot get both to post with no feedback, it just seems to ignore it. I am trying to get both the note and file send to the codebehind for upload in one single post. I'll edit my question to clarify that. – Athanasios Karagiannis May 15 '18 at 00:46
  • @AthanasiosKaragiannis - I'm trying to understand why you are not using the `FormData.append()` properly. The function signature is `(name, value [,file name])` and it appears you are sending `(filename, value)`. The proper thing to do here would be to send `(myfiles[], value, filename)`. What am I missing? – Randy Casburn May 15 '18 at 00:57
  • Possible duplicate of [How to use FormData for ajax file upload](https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload) – Glenn Ferrie May 15 '18 at 13:43
  • @GlennFerrie I'm sure I stumbled upon that one. It doesn't show how the serverside receives both the file and the text. Basically, when the form data is sent, how do I dissect it in the code? Also the "duplicate" seems to be php. I'm working with asp.net. – Athanasios Karagiannis May 15 '18 at 18:50
  • @RandyCasburn I clearly didn't understand FormData that well. Every example I could find of it only showed how the file was accessed in the codebehind but not the other appended data. I figured it out. Thanks so much. – Athanasios Karagiannis May 15 '18 at 18:59

1 Answers1

0

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