问题
I'm was making a drag and drop upload script by reading a bunch of tutorials, but they only cover the javascript part, and i'm having issues on the php part.
I'm uploading a image as this:
$('#drop-zone').bind('drop', drop);
function drop(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer = e.originalEvent.dataTransfer;
traverseFiles(e.dataTransfer.files);
}
traverseFiles makes a foreach loop for every file and calls upload funcion, there i do this:
xhr = new XMLHttpRequest();
//some event listners for processing, on load
xhr.open("post", "core/plugins/upload/upload.class.php", true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
then in php i found using this will get me raw data of the image
$file = file_get_contents('php://input');
EDIT: solution found
$fh = fopen($savedir, 'w') or die("can't open file");
fwrite($fh, $file);
fclose($fh);
回答1:
Assuming you have managed to get the raw file from the PHP input, it's likely going to be base64 encoded. A simple example would be to do this:
<?php
//decode file
$image = base64_decode($file);
// write it
$filename = "myfile.png";
$fh = fopen($filename, 'w') or die("can't open file");
fwrite($fh, $image);
fclose($fh);
Edit See comments, the file wasn't encoded as a result of the request.
回答2:
move_uploaded_file
is not what you want. If you had sent the file with a normal POST request (rather than through Ajax), that's when you'd use move_uploaded_file
.
$file
contains the raw binary data for the image. All you have to do is write that data into a file (taking note to properly handle linebreaks) and you're good to go. Start with fopen
and see how far you get.
I'm assuming that $file
has been successfully populated with the binary data and that you've tested this. If not, then you've got another problem on the javascript side.
Edit: you may also find this helpful.
来源:https://stackoverflow.com/questions/9785948/how-to-save-image-server-side-when-send-from-javascript