0

Now I am in trouble. I need to save a document in my server directory which attached in tag. That is.

<a href='mypdf.pdf'>My pdf</a>

So the mypdf.pdf is dynamically change by javascript but I need to save this document to my server directory. I don't have any idea about this...

1 Answers1

0

What you are trying to acheieve is called file uploading. At javascript/html side it depends how you wish to upload the file.

following question will help you in async file upload using HTML5 How can I upload files asynchronously?

As an alternative you can also take a look at (which provides fallback in case HTML5 file upload is not supported) http://www.uploadify.com/ and http://blueimp.github.io/jQuery-File-Upload/

in case you already have access to a file object and you are using a compatible browser (with HTML5 File API) following method can be used at js side -

function uploadFile(myFileObject) {
    // Open Our formData Object
    var formData = new FormData();

    // Append our file to the formData object
    // Notice the first argument "file" and keep it in mind
    formData.append('my_uploaded_file', myFileObject);

    // Create our XMLHttpRequest Object
    var xhr = new XMLHttpRequest();

    // Open our connection using the POST method
    xhr.open("POST", 'upload.php');

    // Send the file
    xhr.send(formData);
}

at the server side you need a file processing script (an upload handler)

following is a very primitive code from w3schools' site which saves the file in a directory called upload.

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

for more info on the php side file upload and source of the above code check out http://www.w3schools.com/php/php_file_upload.asp

Community
  • 1
  • 1
Mohit
  • 2,239
  • 19
  • 30