Httpcontext receive parameter from jQuery

Asked

Viewed 366 times

2

I’m having a hard time getting a parameter from a registration form to an . ashx.

This is a simple form that will receive registration data and upload a resume. The upload script I downloaded from the net is using jQuery/Ajax and c#/Httphandler.

Follows the codes:

public class file_to_up : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            if (context.Request.QueryString["upload"] != null)
            {
                string pathrefer = context.Request.UrlReferrer.ToString();
                string Serverpath = HttpContext.Current.Server.MapPath("credenciamento\\uploads\\");

                var postedFile = context.Request.Files[0];

                string file;

                //For IE to get file name
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = postedFile.FileName.Split(new char[] { '\\' });
                    file = files[files.Length - 1];
                }
                else
                {
                    file = postedFile.FileName;
                }


                if (!Directory.Exists(Serverpath))
                    Directory.CreateDirectory(Serverpath);

                string fileDirectory = Serverpath;
                if (context.Request.QueryString["fileName"] != null)
                {
                    file = context.Request.QueryString["fileName"];
                    if (File.Exists(fileDirectory + "\\" + file))
                    {
                        File.Delete(fileDirectory + "\\" + file);
                    }
                }

                string ext = Path.GetExtension(fileDirectory + "\\" + file);
                file = Guid.NewGuid() + ext;

                fileDirectory = Serverpath + "\\" + file;

                postedFile.SaveAs(fileDirectory);

                context.Response.AddHeader("Vary", "Accept");
                try
                {
                    if (context.Request["HTTP_ACCEPT"].Contains("application/json"))
                        context.Response.ContentType = "application/json";
                    else
                        context.Response.ContentType = "text/plain";
                }
                catch
                {
                    context.Response.ContentType = "text/plain";
                }

                context.Response.Write("Success");
            }
        }
        catch (Exception exp)
        {
            context.Response.Write(exp.Message);
        }
    }

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

jQuery:

$(function () {
$('#btnFileUpload').fileupload({
    url: 'file-to-up.ashx?upload=start',
    add: function (e, data) {
        console.log('add', data);
        $('#progressbar').show();
        data.submit();
    },
    progress: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progressbar div').css('width', progress + '%');
    },
    success: function (response, status) {
        $('#progressbar').hide();
        $('#progressbar div').css('width', '0%');
        console.log('success', response);
        alert('Enviado');
    },
    error: function (error) {
        $('#progressbar').hide();
        $('#progressbar div').css('width', '0%');
        console.log('error', error);
        alert('Ocorreu um erro e o arquivo não pode ser enviado. Tente novamente');
    }
});
});

I would like the name of the file that currently receives a Guid file = Guid.NewGuid() + ext; received the number of the CPF candidate... Of course you can question.. Ora.. Guid is perfect, because there will never be the possibility of conflicts.. Why then use CPF? First that will not be cumulative the registrations and also because I need to link the file to his CPF to be appreciated by the manager examining the resumes..

I’ve lost a few hairs trying but I couldn’t.. Someone could give a help?

1 answer

1


Hello,

and if you put

$(function () {
    $('#btnFileUpload').fileupload({
        //incluir o CPF no query string....
        url: 'file-to-up.ashx?upload=start&cpf='+$('#ID_DO_FIELD_CPF').val(),
        //restante do seu código....
    });
});

and in the file that handles the upload, you receive the paramtero and rename the file......

//veja que a query string é a mesma do arquivo js....
var cpf= context.Request.QueryString["cpf"];

//com esta variavel vc altera o nome do arquivo...
file = cpf + ext;

Points that you should take into account

  1. Create a function to remove points and strokes from Cpf
  2. Check whether or not it is filled before starting the upload, this may be a problem, you will force the guy to fill in the CPF before uploading
  3. do the creation check because a guy can give up everything even sending the file by ajax

hope I’ve helped....

  • your answer did help! This is what you needed. The suggested checks had already been made. Vlw!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.