1

I used base64 encoded to display image dynamically (by select image).

<img style="width: 412px;" src="data:image/gif;base64,R0lGODlhwAAAAXAAACH5BAEAAPwALA

How to send image to a server? by $.ajax() and without postback.

Thanks in advance

hamed hossani
  • 986
  • 2
  • 14
  • 33

1 Answers1

2
$.ajax({
    type: 'POST', //or get
    url : 'urlToMyServer.aspx',
    data: { img : $('img').attr('src') }
});

If the B64 is'nt really, really long, just send it the regular way ?

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • `data: $('img').attr('src')` this won't work. `data` accepts an object or a query string. – iMoses Dec 16 '12 at 21:43
  • 1
    @iMoses it accepts arbitrary string, which jQuery will send literally as POST request body – Esailija Dec 16 '12 at 21:44
  • 1
    @iMoses - sending a string is'nt a problem, but objects are actually easier to understand in this case I think, so I've edited it. – adeneo Dec 16 '12 at 21:46
  • If so than how do I fetch it on the server side? What's the name of my post variable? As far as I know, if you wanna use a string it should be formated as a query string, such as: `data: 'img=' + $('img').attr('src')` – iMoses Dec 16 '12 at 21:46
  • @iMoses depends on the language/platform, in php you would do `$requestBody = file_get_contents( "php://input");` – Esailija Dec 16 '12 at 21:48
  • @iMoses - it accepts anything, even just an array, jQuery creates the querystring or whatever it needs to send. Not really very good at C#. so how you'd capture that in ASP I'm not sure of. – adeneo Dec 16 '12 at 21:49
  • 2
    If you pass a string, jQuery will not do anything to it, and you have to parse raw request body manually on the server – Esailija Dec 16 '12 at 21:50
  • Ok, you're right :) Though you have to admit it's much more readable to use `$requestBody = $_POST['img']` as well as indicating the name of the variable on the client side. – iMoses Dec 16 '12 at 21:51
  • @adeneo-you says:it accepts anything.i asked you?what's string length? – hamed hossani Dec 16 '12 at 21:52
  • @hamed hossani http://stackoverflow.com/questions/2364840/what-is-the-size-limit-of-a-post-request – iMoses Dec 16 '12 at 21:54
  • Usually post requests are somewhere around 2 megabyte, but it's a server setting, so if you have enough memory you could set it to 2 gigabyte for that matter! – adeneo Dec 16 '12 at 21:54
  • tanks to all,How to upload my image to a server? – hamed hossani Dec 16 '12 at 22:02