Question:
Does AJAX support File Uploads?
Eyes Drinker
2008-04-24 22:36:04 UTC
hi,

does ajax support file uploads ?
i am looking for easy to use PHP/AJAX file upload with progress bar?? anybody knows it?

Thanks
Five answers:
bernz
2008-04-24 22:55:04 UTC
In a way, AJAX *is* file uploads.



AJAX is just a catch-all name for technologies that work together to make pages more dynamic by localizing refresh to regions, instead of the whole page.



The magic ingredient is an XMLHttpRequest object (may be called something else, depending on OS, browser, scripting language, etc) which is like making an HTTP request, just like your browser does to get web pages, but it usually makes the request to a program running on the web server, which knows how to return fragments of a web page, instead of a whole page.



So, you could write your own file-uploader pretty simply. Just have the HTTP request send the contents of the file, and have the corresponding program on the server (host) collect the contents of the file sent through the request object, and dump the contents as a file on its local storage, or even do other crazy stuff like bounce the data elsewhere.



Do some reading on AJAX first (Wikipedia probably has a nice overview) so you get the general idea.



Then look into the XMLHttpRequest object, and how it works. Beware, some browsers use different details (mechanisms, names, etc) -- you can account for these in your scripting, although sometimes you have to use irritating workarounds.



You're probably going to want to learn/know JavaScript and what the DOM is. The progress bar will be a piece of cake using CSS.
purodude
2008-04-24 22:44:10 UTC
I know that Gmail uses Ajax to save email drafts and it supports uploading attachments. But I don't know the specifics of it, good luck.
just "JR"
2008-04-25 03:21:17 UTC
It does.

Long routine here on top... but should work.

I suggest you go to www.SeeMySites.net.

They have a nice file upload in Ajax with progress bar.

Download is free.
Honey_pisces
2008-04-25 00:10:52 UTC
Yes u can import File, while setting it in variable in javascript ,



but for that u have to manually put file content in javascript varaible.

if u using DWR , then its possible directly also



example :



var file = "Content of file"



then simply sending it as parameter to XMLHTTPREQUEST
anonymous
2008-04-24 23:04:50 UTC
<?php

$upload_dir = "/var/www/anyexample/aeu"; // File store path

$web_upload_dir = "/aeu"; // File web path

$tf = $upload_dir.'/'.md5(rand()).".test";

$f = @fopen($tf, "w");

if ($f == false)

die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'

or something like this");

fclose($f);

unlink($tf);



//upload

if (isset($_POST['fileframe']))

{

 $result = 'ERROR';

 $result_msg = 'No FILE field found';



 if (isset($_FILES['file'])) // borwse receive

 {

  if ($_FILES['file']['error'] == UPLOAD_ERR_OK)

  {

   $filename = $_FILES['file']['name'];

   move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);   

   $result = 'OK';

  }

  elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)

   $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';

  else

   $result_msg = 'Unknown error';

 }



 echo '<html><head><title>-</title></head><body>';

 echo '<script language="JavaScript" type="text/javascript">'."\n";

 echo 'var parDoc = window.parent.document;';

 '

 if ($result == 'OK')

 {

  echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';

  echo 'parDoc.getElementById("filename").value = "'.$filename.'";';

  echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';

  echo 'parDoc.getElementById("upload_button").disabled = false;';

 }

 else

 {

  echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';

 }



 echo "\n".'</script></body></html>';

 exit();

}



function safehtml($s)

{

 $s=str_replace("&", "&", $s);

 $s=str_replace("<", "<", $s);

 $s=str_replace(">", ">", $s);

 $s=str_replace("'", "'", $s);

 $s=str_replace("\"", """, $s);

 return $s;

}



if (isset($_POST['description']))

{

 $filename = $_POST['filename'];

 $size = filesize($upload_dir.'/'.$filename);

 $date = date('r', filemtime($upload_dir.'/'.$filename));

 $description = safehtml($_POST['description']);



 $html =<<<END

 <html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head>

 <body>

  <h1>{$filename}</h1>

  <p>This is a file information page for your uploaded file. Bookmark it, or send to anyone...</p>

  <p>Date: {$date}</p>

  <p>Size: {$size} bytes</p>

  <p>Description:

  <pre>{$description}</pre>

  </p>

  <p><a href="{$web_upload_dir}/{$filename}" style="font-size: large;">download file</a><br>

  <a href="{$PHP_SELF}" style="font-size: small;">back to file uploading</a><br>

  <a href="{$web_upload_dir}/upload-log.html" style="font-size: small;">upload-log</a></p>

  <br><br>Example by <a href="http://www.anyexample.com/">AnyExample</a>

 </body></html>

 END;

 

 $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");

 fwrite($f, $html);

 fclose($f);

 $msg = "File {$filename} uploaded,

 <a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";



 $f = fopen($upload_dir."/upload-log.html", "a");

 fwrite($f, "<p>$msg</p>\n");

 fclose($f);



 setcookie('msg', $msg);

 header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);

 exit();

}



if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '')

{

 if (get_magic_quotes_gpc())

  $msg = stripslashes($_COOKIE['msg']);

 else

  $msg = $_COOKIE['msg'];

  setcookie('msg', '');

}

?>

<!-- Beginning of main page -->

<html><head>

<title>IFRAME Async file uploader example</title>

</head>

<body>

<?php

 if (isset($msg))

  echo '<p style="font-weight: bold;">'.$msg.'</p>';

?>

<h1>Upload file:</h1>

<p>File will begin to upload just after selection. </p>

<p>You may write file description, while you file is being uploaded.</p>



<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">

 <input type="hidden" name="fileframe" value="true">

 <!-- Target of the form is set to hidden iframe -->

 <!-- From will send its post data to fileframe section of this PHP script (see above) -->



 <label for="file">text file uploader:</label><br>

 <!-- JavaScript is called by OnChange attribute -->

 <input type="file" name="file" id="file" onChange="jsUpload(this)">

</form>

<script type="text/javascript">

/* This function is called when user selects file in file dialog */

function jsUpload(upload_field)

{

 // this is just an example of checking file extensions

 // if you do not need extension checking, remove

 // everything down to line

 // upload_field.form.submit();

 

var re_text = /\.txt|\.xml|\.zip/i;

 var filename = upload_field.value;



 /* Checking file type */

 if (filename.search(re_text) == -1)

 {

  alert("File does not have text(txt, xml, zip) extension");

  upload_field.form.reset();

  return false;

 }



 upload_field.form.submit();

 document.getElementById('upload_status').value = "uploading file...";

 upload_field.disabled = true;

 return true;

}

</script>

<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">

</iframe>

<!-- For debugging purposes, it's often useful to remove

"display: none" from style="" attribute -->



<br>

Upload status:<br>

<input type="text" name="upload_status" id="upload_status"

value="not uploaded" size="64" disabled>

<br><br>



File name:<br>

<input type="text" name="filenamei" id="filenamei" value="none" disabled>



<form action="<?=$PHP_SELF?>" method="POST">

 <!-- one field is "disabled" for displaying-only. Other, hidden one is for sending data -->

 <input type="hidden" name="filename" id="filename">

 <br><br>



 <label for="photo">File description:</label><br>

 <textarea rows="5" cols="50" name="description"></textarea>



 <br><br>

 <input type="submit" id="upload_button" value="save file" disabled>

</form>

<br><br>

<a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a>

<br><br><br>



Example by <a href="http://www.handandaily.com/">AnyExample</a>

</body>

</html>


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...