blueimp / jQuery-File-Upload

File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.
https://blueimp.github.io/jQuery-File-Upload/
MIT License
30.96k stars 7.96k forks source link

Error: SyntaxError: JSON.parse: unexpected character #517

Closed nmorizet closed 12 years ago

nmorizet commented 13 years ago

I'm trying to create a very simple page to upload some files to my server, using the code we can find in the 'index.html' from the "example" directory of the jQuery File Upload plugin.

All the links to the jQuery sources, folders where files will be sent (i.e. 'files' and 'thumbnails'), 'upload.php' page, files permissions, etc. have been set carefully !

Selecting a file, getting a thumbnail in case of an image and the loading process seem to work perfectly fine BUT, at the end, I got this error message : "Error: SyntaxError: JSON.parse: unexpected character" ! And I can't find my uploaded file anywhere !

I really don't know what's wrong and it's important for me to fix this as soon as possible for my project.

Please help me ! :) Thx !

ashkansiroos commented 13 years ago

I have the same problem in asp.net, but when I click on start upload, I can find my files on my code and everything works fine, but on UI , user always see "Error: SyntaxError: JSON.parse: unexpected character"

bullenb commented 13 years ago

I had the same problem. I solved it by allowing writing (chmod) to the directories that the example is writing to (files & thumbnails).

It might be worth including a note on this in the setup documentation....

nmorizet commented 13 years ago

Well, I also changed those directories to '755' but it didn't solve the problem..

I could have noticed that the file 'upload.php' (in the 'example' folder) is not processing normally, I have this error :

"Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' ", because of the line including "private $options" (I read that this is a PHP 5 declaration).

So, I checked what PHP version I have on my server and it turned out to be PHP 4.4.4 version !!

Is it necessary to have a PHP version > 5.2 to run the 'File Upload Plugin' ??

Because I put a '.htaccess' file at the root of my website folder, transfering it by FTP (ASCII mode) and containing one line which is "SetEnv PHP_VER 5" but didn't do the trick.. :(

What do you suggest ?

namelessjon commented 13 years ago

It's definitely not necessary to run php of any particular version. I use the plugin with ruby (and sinatra), for example. The plugin itself just sends data in a certain way, and expects to get back json with a few required fields.

The example code is probably written for php 5.2 though, and it seems it needs some modification for earlier versions.

nmorizet commented 13 years ago

You're right, we can use the plugin in several ways.

But it's easier for me to implement this plugin directly in PHP, so do you know if there is a previous version of the plugin where the code is not written for PHP 5.2, thus I could use it ?

namelessjon commented 13 years ago

I'm not a php coder, so I have no idea.

brianwood commented 13 years ago

use Firebug on FireFox and you can watch the console pane for a POST response. I have the same error and found out that my php.ini allowed_memory_size is too low to perform my resize commands...which was failing my entire upload.

Brakus commented 12 years ago

Hello! I have a similar problem. I'm using PHP and Zend Framework

Error: SyntaxError: JSON.parse: unexpected character is the error that I get when I'm trying to upload image files.

When I use Firebug on FF and watch the console pane for a POST response as @brianwood suggested I get this


Warning: imagepng() [function.imagepng]: Unable to open '/Applications/XAMPP/xamppfiles/htdocs/mts/application/modules/design/models/vendors/thumbnails/Screen shot 2011-10-12 at 1.49.33 PM.png'

for writing: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/mts/application/modules/design/models/vendors/Upload.php on line 145
[{"name":"Screen shot 2011-10-12 at 1.49.33 PM.png","size":160995,"type":"image\/png","url":"\/\/files\/Screen%20shot%202011-10-12%20at%201.49.33%20PM.png","delete_url":"\/index.php?file=Screen%20shot%202011-10-12%20at%201.49.33%20PM.png",

by taking a look I saw that there is a problem in the upload.php within a "private function create_scaled_image" specifically in the line 145

------------------Upload.php--------

private function create_scaled_image($file_name, $options) { $file_path = $this->options['upload_dir'].$file_name; $new_file_path = $options['upload_dir'].$file_name; list($img_width, $img_height) = @getimagesize($file_path); if (!$img_width || !$img_height) { return false; } $scale = min( $options['max_width'] / $img_width, $options['max_height'] / $img_height ); if ($scale > 1) { $scale = 1; } $new_width = $img_width * $scale; $new_height = $img_height * $scale; $new_img = @imagecreatetruecolor($new_width, $new_height); switch (strtolower(substr(strrchr($file_name, '.'), 1))) { case 'jpg': case 'jpeg': $src_img = @imagecreatefromjpeg($file_path); $write_image = 'imagejpeg'; break; case 'gif': @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0)); $src_img = @imagecreatefromgif($file_path); $write_image = 'imagegif'; break; case 'png': @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0)); @imagealphablending($new_img, false); @imagesavealpha($new_img, true); $src_img = @imagecreatefrompng($file_path); $write_image = 'imagepng'; break; default: $src_img = $image_method = null; } $success = $src_img && @imagecopyresampled( $new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height ) && $write_image($new_img, $new_file_path); //this is line 145 !!!! // Free up memory (imagedestroy does not delete files): @imagedestroy($src_img); @imagedestroy($new_img); return $success; }

katanacrimson commented 12 years ago

Check your chmod settings - sounds like an unwriteable directory, or you're uploading overtop a file already in existence that doesn't allow you to write to it.

Also check chown.

You should also be warned that you shouldn't be preserving filenames on upload. High risk activity, it leaves you open to possible exploitation. You should be using a randomly generated name instead, and piping the file through a script while sending the appropriate headers to prevent certain brain-damaged browsers (lolIE) from being stupid and trying to execute the file as something like, say, HTML or javascript.

Brakus commented 12 years ago

I was pointing it to the wrong directory. A very stupid mistake from my side.

jorgemarcial commented 12 years ago

Hi , I had the same problem and find an easy solution by creating a VirtualHost with Apache.

I thought it was not necessary because the main file is a .html

sorry for my poor english and good luck!

Avani99 commented 12 years ago

Hii guys ... I have same prob ,,, :(

I think something is missing from my side ,,,

as when I checked req - response from firebug ,,,

my post data is ,.,,

---------------------------1705044916800534631589515198--

& response is ,, my whole page again :(

so in browser its returning me ,,,

30.jpg Error: SyntaxError: JSON.parse: unexpected character

one more thing I have checked folder permission .. its 777 for now, but than also its not helped me :(

pl help me for this asap ... as my proj deadline is too near ,,,

thanking you all in advance ,,,,,

Artform commented 12 years ago

I just set the directory permissions to the following to test: 755 - error 775 - error 766 - error 776 - error 777 - pass

It appears 777 is the best permission to use to reduce errors. This must be done one your uploads directory and any other directory you may be moving resized images to after upload.

katanacrimson commented 12 years ago

@A3sthetix if it takes chmod 777 to work, you've likely got the directory owned by the wrong user. 755 will work if the directory is owned by the user that php is running under (under standard ubuntu LAMP setup, this should be www-data)

Artform commented 12 years ago

I totally agree with that, but even through I used PHP to create the directory, I've had to use 777. Must be something odd with my LAMP setup. I think the users that commented above are in the same boat.

katanacrimson commented 12 years ago

it may not actually be set to the chmod you think it is on the mkdir call (which is how it sounds you're doing it off the bat) - be sure you used umask() properly around the mkdir - http://us2.php.net/manual/en/function.mkdir.php#95891

akougblenou commented 12 years ago

I am getting the same error "Error: SyntaxError: JSON.parse: unexpected character".

I am working with Zend Framework and followed the read me (which mean my upload.php has been replaced by a controller). Now it seems that the JSON does never get created and that on POST the whole page gets posted. I have spent quite some time on it and I just can't seem to figure it out.

There may be something missing in my version but as there is no complete example of this script in Zend, I am not sure what to do... can someone advise please ?

reuth1982 commented 12 years ago

EN ESPAÑOL El problema es del script... revisar el codigo fuente de upload.php u modificaciones realizadas, rutas, etc. puede deberse a llamar un objeto inexistente...

Gread commented 12 years ago

i had the same problem, and the problem was because i was returning a view or anything , but the correct need that my server return a json in this formart: [{"name":"picture1.jpg","size":902604,"url":"\/\/example.org\/files\/picture1.jpg","thumbnail_url":"\/\/example.org\/thumbnails\/picture1.jpg","delete_url":"\/\/example.org\/upload-handler?file=picture1.jpg","delete_type":"DELETE"},

akougblenou commented 12 years ago

I forgot to post the solution I had found. Basically the JSON was not created has I did not identfy that there was an XmlHttpRequest going and disable the layout to get the JSON:

  //boolean needed to check that there has been JSON request
  if($this->_request->isXmlHttpRequest())        
  {
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
    $this->upload();
  }

this bit of code in my action function solved this problem for me. Hope it helps!

jmacreativo commented 12 years ago

En español: Tan solo cambiar los permisos de la carpeta:

777 php/ 777 php/thumbnails 777 php/files

And everything start to working perfect :)

jose-granados commented 12 years ago

Finally I got around this problem. Ok first, a little of background:

I needed to create a specific folder array for my application, each new item would get a img folder (large, grid, thumbnail) and a documents folder (for pdfs and word files), so, in index.php inside the server folder, not mine, I did an overide of the options, like this : require('upload.class.php'); $brand = $_GET['brand']; $item = $_GET['item']; $type = $_GET['type']; if($type == 'img'){ $upload_handler = new UploadHandler(array( 'upload_dir' => "../../files/$brand/$item/$type/", 'upload_url' => "../../files/$brand/$item/$type/", 'delete_type' => 'POST', 'image_versions' => array( 'thumbnail' => array( 'upload_dir' => "../../files/$brand/$item/" . 'thumbnails/', 'upload_url' => "../../files/$brand/$item/" . 'thumbnails/' ), 'grid' => array( 'upload_dir' => "../../files/$brand/$item/" . 'grid/', 'upload_url' => "../../files/$brand/$item/" . 'grid/' ), 'modal' => array( 'upload_dir' => "../../files/$brand/$item/" . 'modal/', 'upload_url' => "../../files/$brand/$item/" . 'modal/' ) ), )); }else{ $upload_handler = new UploadHandler(array( 'upload_dir' => "../../files/$brand/$item/$type/", 'upload_url' => "../../files/$brand/$item/$type/", 'delete_type' => 'POST' )); }

This would only let me chose the destination folder of the upload, as I intendet to do, all the rest of the options were coded in the 'upload.class.php' file, like this: function __construct($options=null) { $this->options = array( 'script_url' => $this->getFullUrl().'/', 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/', 'upload_url' => $this->getFullUrl().'/files/', 'param_name' => 'files', // Set the following option to 'POST', if your server does not support // DELETE requests. This is a parameter sent to the client: 'delete_type' => 'POST', // The php.ini settings upload_max_filesize and post_max_size // take precedence over the following max_file_size setting: 'max_file_size' => null, 'min_file_size' => 1, 'accept_file_types' => '/.+$/i', // The maximum number of files for the upload directory: 'max_number_of_files' => null, // Image resolution restrictions: 'max_width' => 0, 'max_height' => 0, 'min_width' => 1, 'min_height' => 1, // Set the following option to false to enable resumable uploads: 'discard_aborted_uploads' => true, // Set to true to rotate images based on EXIF meta data, if available: 'orient_image' => false, 'image_versions' => array( // Uncomment the following version to restrict the size of // uploaded images. You can also add additional versions with // their own upload directories: 'modal' => array( 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/modal/', 'upload_url' => $this->getFullUrl().'/modal/', 'max_width' => 800, 'max_height' => 600 ), 'thumbnail' => array( 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/thumbnails/', 'upload_url' => $this->getFullUrl().'/thumbnails/', 'max_width' => 90, 'max_height' => 90 ), 'grid' => array( 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/grid/', 'upload_url' => $this->getFullUrl().'/grid/', 'max_width' => 150, 'max_height' => 120 ) ) ); if ($options) { $this->options = array_replace_recursive($this->options, $options); } }

With this configuration, on my LAMP production server, it was running smooth as silk, but when I uploaded everything to the live server, it displayed this awfull error we all are getting. My file permisions were 0777 already, just as the early posts of this thread suggest, so it had to be something else.

After investigating the matter a little further, If you have override options, the uploader runs an if statement, located in the upload.class.php file:

    if ($options) {
        $this->options = array_replace_recursive($this->options, $options);
    }

The function array_replace_recursive is exclusive for php 5.3 or greater, and my live web server was running 5.2. According to this source: https://github.com/blueimp/jQuery-File-Upload/issues/496 in order to run this script on php 5.2 servers, you should have to add a custom-made function that would replace the incompatible one, source code is here: http://de.php.net/manual/en/function.array-replace-recursive.php#92574

So, adding this piece of code before the 'require' statement, inside index.php, I was able to run without problems my application. I hope this would help you as much as it did for me.