Languages

Menu
Sites
Language
Uploading Files with Ajax doesn't work

I'm writing the code that have to upload file to the server:

<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />

 

<script>
   var client = new XMLHttpRequest();
  
   function upload() 
   {
      var file = document.getElementById("uploadfile");
     

      var formData = new FormData();

      formData.append("upload", file.files[0]);
      var uri = "http://cs418417.vkontakte.ru//upload.php?act=do_add&mid=219171498&aid=-3&gid=0&hash=1d0312a6d881c5bcbd8a32892fdde3b9&rhash=1a32741be051f0e3b7e7777393f4dc98&swfupload=1&api=1&mailphoto=1";
   
      client.open("post", uri, true);
      client.setRequestHeader("Content-Type", "multipart/form-data");
      client.send(formData);  /* Send to server */ 
   }
     

   client.onreadystatechange = function() 
   {
      if (client.readyState == 4 && client.status == 200) 
      {
         alert(client.statusText);
      }
   }
</script>

 

But the code uploads file to the server not correctly. For example when i use simple form code in html:

<form action="http://cs418417.vkontakte.ru//upload.php?act=do_add&mid=219171498&aid=-3&gid=0&hash=1d0312a6d881c5bcbd8a32892fdde3b9&rhash=1a32741be051f0e3b7e7777393f4dc98&swfupload=1&api=1&mailphoto=1" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file1" id="file1"><br>
<input type="submit" name="submit" value="Submit">
</form>

The response that i receives is: 

{"server":418417,"photo":"[{\"photo\":\"58dbd7fca1:x\",\"sizes\":[[\"s\",\"418417498\",\"9165\",\"-vPwxuYh3a0\",75,75],[\"m\",\"418417498\",\"9166\",\"SCen1cdqbqA\",75,75],[\"x\",\"418417498\",\"9167\",\"1XqJ_4BjVbc\",75,75],[\"o\",\"418417498\",\"9168\",\"8KZwWQoGt-s\",75,75],[\"p\",\"418417498\",\"9169\",\"4QYAd439mMU\",75,75],[\"q\",\"418417498\",\"916a\",\"XcshUdJ3rhg\",75,75],[\"r\",\"418417498\",\"916b\",\"J5k9F5GwslA\",75,75]],\"kid\":\"8b07b778321c8d8ad2a5a1f9bb9cc924\"}]","hash":"fba9b21f075968f161778c30b443d901"}

But in my first code response is: 

{"server":418417,"photo":"[]","hash":"4e161711a754523972bc69581e21bc2d"}

Where  is the problem?  Thanks in advance and sorry for my English!

This is VK server api: http://vk.com/pages?oid=-17680044&p=Uploading_Files_to_the_VK_Server_Procedure

Responses

1 Replies
Lakshmi Grandhi

Hi,

Replace your code

formData.append("upload", file.files[0]);

with

formData.append("file", file.files[0]);