I'm using form data for uploading files code given below
var formData = new FormData();
/* Add the file */
formData.append("qqfile", file);
xhr.open("post", 'upload.php', true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(formData); /* Send to server */
in upload.php my code is given below
$fileReader = fopen('php://input', "r");
$fileWriter = fopen($this->_destination_file, "w+");
while(true) {
$buffer = fgets($fileReader, 4096);
if (strlen($buffer) == 0) {
fclose($fileReader);
fclose($fileWriter);
return true;
}
fwrite($fileWriter, $buffer);
}
return false;
when i'm trying to upload pdf file it's working perfectly, when I'm trying to upload .xls file,file is uploaded but when i open xls file getting non readable character.
Related
I am developing custom WordPress plugin. In this plugin, I am trying to upload files into wp-content\uploads\passports (folder path).
I don't face any error message when uploading file. Although it shows File has been uploaded successfully. message, but there is no any uploaded file in the folder.
Here is my code:
trip-form.php
<tr><td cospan="4">Please attach a scanned copy of your:</td></tr>
<tr>
<td>Passport: </td>
<td colspan="3"><input type="file" name="passport" id="passport"/></td>
</tr>
<tr>
<td></td>
<td colspan="3"><div id="dropBox">
<p>Select file to upload</p>
</div></td>
</tr>
script.js
// Add events
$j('input[type=file]').on('change', fileUpload);
// File uploader function
function fileUpload(event){
alert('fileUpload');
//notify user about the file upload status
$j("#dropBox").html(event.target.value+" uploading...");
//get selected file
files = event.target.files;
//form data check the above bullet for what it is
var data = new FormData();
var web_url = document.location + '';
var path = web_url.substring(0,web_url.lastIndexOf('/'));
path = path.substring(0,path.lastIndexOf('/'));
path = path + '/wp-content/plugins/trip-form/pages/uploadfile.php';
//file data is presented as an array
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileExtension = ['jpeg', 'jpg', 'pdf'];
if ($j.inArray($j('#passport').val().split('.').pop().toLowerCase(), fileExtension) == -1) {
$j("#dropBox").html("Only formats are allowed : "+fileExtension.join(', '));
}else{
//append the uploadable file to FormData object
data.append('file', file, file.name);
//create a new XMLHttpRequest
var xhr = new XMLHttpRequest();
//post file data for upload
xhr.open('POST', path, true);
xhr.send(data);
xhr.onload = function () {
//get response and show the uploading status
var response = JSON.parse(xhr.responseText);
if(xhr.status === 200 && response.status == 'ok'){
$j("#dropBox").html("File has been uploaded successfully.");
}else{
$j("#dropBox").html("Some problem occured, please try again.");
}
};
}
}
}
uploadfile.php
<?php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
//generate unique file name
$fileName = time().'_'.basename($_FILES["file"]["name"]);
//file upload path, targetdir is correct
$targetDir = "../../../uploads/passports/";
$targetFilePath = $targetDir . $fileName;
//upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
//if (file_exists ( $targetDir."testing.txt" )){
$response['status'] = 'ok';
}else{
$response['status'] = 'err';
}
//render response data in JSON format
echo json_encode($response);
?>
I have no idea what is wrong. Any help would be appreciated.
Thanks.
Can you please change your uploads folder permission. Make it 755.
I am using a nice tool called cropit and built a little application: You can check it out here
Now I tried to save the image instead of opening it in a new windows. I used this:
JQUERY:
$('.export').click(function() {
var imageData = $('#image-cropper').cropit('export');
$.post('upload.php', { imageData: imageData }, function() {
alert("success");
})
});
PHP:
$imageData = $_POST['imageData'];
$decoded = urldecode($imageData);
$exp = explode(',', $decoded);
$base64 = array_pop($exp);
$data = base64_decode($base64);
$file = 'data.png';
file_put_contents($file, $data);
In result I get a PNG file in my directory, which does not get an error when I open (I can zoom and do stuff), but it is blank. How do I make the image appear in the file?
I have this jquery code:
$('input[type=file]').on('change', uploadFiles);
function uploadFiles(event) {
var data = new FormData();
var files = event.target.files;
for(var i = 0;i<files.length;i++){
data.append("file_"+i, files[i]);
}
data.append('dir_name',current_directory);
apicall('upload.php','POST',data,fileUploaded);
}
Then in php file:
<?php
$data = array();
$allFiles = scandir($_REQUEST['dir_name']);
if(isset($_FILES))
{
$error = false;
$uploaddir = $_REQUEST['dir_name'];
foreach($_FILES as $file)
{
echo $file['error'];
echo $file['tmp_name'];
$new_name = $file['name'];
move_uploaded_file($file['tmp_name'], $uploaddir .'/'.$file['name']);
}
}
else
{
//some code here
}
echo json_encode($error);
?>
Now this works and everything, I can upload any file and multiple files at a time too. But it causes the memory Firefox uses to skyrocket and never come down again. It is proportional to the file I upload I think, but way way bigger. I read in the manual that move_uploaded_file() deletes the temporary file, so that can't be the problem. The only thing that helps is to close firefox and open it up again. Can somebody please tell me why this happens and how to make it stop?
If it matters, I am using XAMPP to test all this out on localhost.
This does not happen in chrome.
I'm trying to upload files using php and I am copying and renaming files from other instances that are actually working (uploading pics). But for some reason the form is not passing (POST) any file that is NOT an image :-/
So, in resume, I am getting this (Google) 'request payload' for an image file:
------WebKitFormBoundaryrHOYostaC2KnUDlD
Content-Disposition: form-data; name="uploaded_file[]"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryrHOYostaC2KnUDlD--
But this for txt or pdf files:
------WebKitFormBoundaryc1RJOtSOpYKAZiBz--
Here is the form and script (functions are to avoid the user to click 'Submit', those work good):
echo '
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("uploaded_file");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("uploaded_file");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>';
echo '
<form enctype="multipart/form-data" target="_blank" name="send_file" id="send_file" method="post" action="file_upload.php">
<input type="file" class="hide button" id="uploaded_file" name="uploaded_file" onChange="Handlechange();"/>
<button type="submit" id="btn">Upload!</button>
</form>';
echo '
<div onclick="HandleBrowseClick();" id="fakeBrowse" >Load a file</div>
<input type="text" id="filename" size="50" readonly="true" />
';
So, since it's not passing anything, in my file_upload.php I get the "ERROR: Please browse for a file before clicking the upload button." or "Invalid argument supplied for foreach()" (if I expect an array) error.
I tried using application/x-www-form-urlencoded allowing the same result. Now for those who get mad if there is no question marks: Why the form works fine with images but not so with other kind of files? What am I dong wrong?
Here is the first few lines of file_upload.php (I don't think it's necessary but you never know):
$target = "../files/temp/";
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
if ($error != UPLOAD_ERR_OK) { echo "error"; die;}
$fileName = $target . $_FILES["uploaded_file"]["name"][$key]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$key]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$key]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$key]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$key]; // 0 for false... and 1 for true last $key!!!
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$fileName = strtolower($fileName);
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.";
exit();
}
Finally, some more js:
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Loading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
}).done(function (res) {
document.getElementById("response").innerHTML = res;
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
});
}
}, false);
where changing contentType doesn't make any diference
THANKS!!!
You have to define the MIME types for your files. For example
.pdf application/pdf
.doc application/msword
Okay, my bad. The js file has an image filter. It started working right away after I removed it.
I all,
I'm trying to upload an xls file using the HTML5 API.
I already have a script which is working great for images.
It's also working with an xls file except the fact that I can't open the file using excel once it has been uploaded...
If I compare the size, the orignal file is 251 904 octets while the upload one is 251 911 octets. I don't know if that matter.
Here is what i've done :
Javascript:
reader = new FileReader();
reader.onloadend = function(evt) {
that.file = evt.target.result;
};
reader.readAsDataURL(file); // I've also try with readAsText but it's worse
the file is send using Sproutcore Framework:
SC.Request.postUrl(url).json()
.notify(this, 'fileUploadDidComplete', fileName)
.send({ fileName: fileName, file: file });
PHP:
$httpContent = fopen('php://input', 'r');
$json = stream_get_contents($httpContent);
fclose($httpContent);
$data = json_decode($json, true);
$file = base64_decode($data['file']);
$fileName = substr(md5(time().rand()), 0, 10).$data['fileName'];
$filePath = GX_PATH."/files/tmp/".$fileName;
$handle = fopen($filePath, "w");
fwrite ($handle, $file);
fclose($handle);
I hope somebody will help me to find what is wrong.
Thanks in advance.
EDIT:
I find another way which work on more browsers. I've discover FormData !
formData = new FormData();
formData.append("file", file);
SC.Request.postUrl(url).notify(this, 'formDataDidPost').send(formData);
This way, the PHP code is more simple :
$_FILES['file'];
I have done this using following method
$out = fopen($fileUploadPath ,"wb");
$in = fopen("php://input", "rb");
stream_copy_to_stream($in,$out);
This is just 3 methods I used to write the uploaded content to the server. Try it and see