Search code examples
jqueryasp.netajaxmultipartform-datajquery-file-upload

files and data upload without form and with formData jquery and asp.net


(...)

EDIT:

// Client side

var $elem = $("a.attachMessageBtn");
var evtOnClick = $elem.attr('onclick');
var postData = new FormData();
postData.append("FID", FID);
postData.append("messageText", messageToSend);

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

$.ajax(
{
    url: ajaxUrl + "?a=setNewMessage",
    type: "POST",
    data: postData,
    cache: false,
    processData: false,
    contentType: false,
    forceSync: false,
    enctype: "multipart/form-data",
    beforeSend: function (jqXHR, settings)
    {
        // Something being done here.
    },
    success: function (data, textStatus, jqXHR)
    {
        // Something being done here.
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        // Something being done here.
    },
    complete: function (jqXHR, textStatus)
    {
        // Something being done here.
    }
});

// Server side

string sMessageText = Request.Form["messageText"];
int nFID = 0;

if (!string.IsNullOrEmpty(sMessageText) && int.TryParse(Request.Form["fid"] + "", out nFID))
{
    if (Request.Files != null)
    {
        int nFilesCount = Request.Files.Count;

        if (nFilesCount > 0 && nFilesCount <= 3)
        {
            foreach (string file in Request.Files)
            {
                // Specific code here that has always been working.
            }
        }
    }      
} 

EDIT 2

OK, finally got to both the files and the data, but now I once again face an issue of looping the message.

Say I sent a message with one attachment; then I send another message with, e.g., 2 attachments -> this second message will be sent twice; then I send another message, regardless of the number of attachments -> it will be sent 3 times.

How come I solve this, since the code I have is the above one?

Any help, please?

Thank you very much in advance.


Solution

  • I actually ended up solving this problem while doing the same I answered here multiple file upload jquery asp.net add, remove then add again.

    For the files I used the for loop, and then appended the rest of the data to the formData obj.

    Everything working, for now...