AIR - Load local file to web server - php

I try to upload file from local system to web server.
My application is desktop application and I work with php server.
Find below my code
In flex
var dropfiles:Array = evt.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
for each (var file:File in dropfiles){
var fileFormat:String = file.extension;
var fileUrl:String = file.url;
var fileName:String = file.name;
var fileDate:Date = file.creationDate;
var objAdd:Object= new Object();
objAdd.titre=fileName;
objAdd.date=fileDate;
objAdd.url=fileUrl;
DP_PAT_COURR_ENT.addItem(objAdd);
var myFileDir:String=getPatPath(monIdPatient);
var urlCopy:String = new urlManager().urlCourriersPatLoad()+myFileDir;
var rq:URLRequest = new URLRequest(new urlManager().urlService() + "upload.php");
rq.method = URLRequestMethod.POST;
var varphp:URLVariables = new URLVariables();
varphp.userID = monIdPatient;
varphp.url = myFileDir;
rq.data = varphp;
file.upload(rq, 'Filedata');
}
In PHP
<?php
if(isset($_POST['myFileDir']))
$patRoot=$_POST['myFileDir'];
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = $_FILES['Filedata']['name'];
$file_path = $_SERVER['DOCUMENT_ROOT'].$patRoot";
//checks for duplicate files
if(!file_exists($file_path."/".$file_name)) {
//complete upload
$filestatus = move_uploaded_file($file_temp,$file_path."/".$file_name);
if(!$filestatus) {
$success = "false";
array_push($errors,"Upload failed. Please try again.");
}
}
else {
$success = "false";
array_push($errors,"File already exists on server.");
}
echo $file_path;
With those code message "Error #2044: Unhandled IOErrorEvent:" appear on flex.
Thanks for helping

There are many examples out there.
http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/

Related

Working with $_FILES and ZipArchive (PHP and Angular) - incomplete file being downloaded

I have an angularJS based project with a PHP server. The goal at this point is to take a .jar file, and add json file to the META-INF folder in the .jar file and then download it back on the front end. Current solution seems to return an incomplete JAR file. It is openeable with 7Zip, but there is no content within the archive. I am unsure if the issue is the PHP and returning the file or the Angular. I am open to suggestions to do this differently.
My JS in the controller:
//Upload the Two Files:
exportFile = document.getElementById('jar-file-export');
exportFile.addEventListener('change',(event)=>{
//Get Jar File, and Save name for later use.
let i = document.getElementById('jar-file-export');
let formData = new FormData();
formData.append('jar', i.files[0]);
$scope.export.filename = i.files[0].name;
//GET JSON File:
let tFile = new Blob([JSON.stringify($scope.export.file)], {type: 'application/json'});
formData.append('descriptor',tFile);
$http({
method:"POST",
url:"assets/api/fileExport.php",
data: formData,
headers:{"Content-Type":undefined},
dataType: 'text',
mimeType: 'text/plain; charset=x-user-defined',
}).then(function success(response){
//saveAs = fileSaver.js
console.log('File Export,Success',response.data);
let data = response.data;
//Code copied from StackOverFlow:
let newContent = "";
for (var i = 0; i < data.length; i++) {
newContent += String.fromCharCode(data.charCodeAt(i) & 0xFF);
}
var bytes = new Uint8Array(newContent.length);
for (var i=0; i<newContent.length; i++) {
bytes[i] = newContent.charCodeAt(i);
}
blob = new Blob([bytes], {type: "application/zip"})
saveAs(blob, $scope.export.filename);
},function error(response){
console.log('File Export,error',response);
});
})
PHP:
<?php
switch($_SERVER["REQUEST_METHOD"]) {
case("POST"):{
$zip = new ZipArchive;
if ($zip->open($_FILES['jar']['tmp_name']) === true){
$zip->open($_FILES['jar']['tmp_name']);
$zip->addFile($_FILES['descriptor']['tmp_name'],file_get_contents($_FILES['descriptor']['tmp_name']));
$zip->close();
echo (file_get_contents($_FILES['jar']['tmp_name']));
}
break;
}
}
Additionally, I have tried just opening the JAR file and then returning it back to the client, and I still get an empty (but openable) jar file. The below results in a JAR that has a META-INF folder:
PHP:
<?php
switch($_SERVER["REQUEST_METHOD"]) {
case("POST"):{
$zip = new ZipArchive;
$newZip = new ZipArchive;
if ($zip->open($_FILES['jar']['tmp_name']) === true){
echo (file_get_contents($_FILES['jar']['tmp_name']));
}
break;
}
}
Any suggestions here would be greatly appreciated. Thanks
On going through several iterations with lots of SO answers - I discovered that the PHP wasn't properly referencing the file location and modified it so that the PHP moved the files to temp folder.
$jar = $_FILES["jar"]["tmp_name"];
$desc = $_FILES["desc"]["tmp_name"];
$folder = "temp/";
$jar_name = $_FILES["jar"]["name"];
$desc_name = $_FILES["desc"]["name"];
move_uploaded_file($jar,$folder.$jar_name);
move_uploaded_file($desc,$folder.$desc_name);
//Open the Jar, add the descriptor and return the file name:
$zip = new ZipArchive();
if ($zip->open($folder.$jar_name) === TRUE){
$zip->addFile($folder.$desc_name,"META-INF/data.json");
$zip->close();
echo json_encode($jar_name);
} else {
echo "Failed to Open the JAR file";
}

Upload multiple files to server side with php from dart

.dart
Future<http.Response> uploadFile(String fileName, List<int> fileBytes) async {
try {
var request = new http.MultipartRequest("POST", Uri.parse("https://****/***/fileupload.php"));
for (var i = 0; i < uploadedImage.length; i++) {
selectedFilesBytes = List.from(uploadedImage[i]);
request.files.add(http.MultipartFile.fromBytes('file', selectedFilesBytes, contentType: MediaType('application', 'octet-stream'), filename: files[i].name));
}
print("request.files.length");
print(request.files.length);
var streamedResponse = await request.send();
return await http.Response.fromStream(streamedResponse);
} catch (e) {
print(e);
}
fileupload.php
<?php
// Count total files
$countfiles = count($_FILES['file']);
error_log($countfiles);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
}
?>
Hi,
I have a problem about file upload from dart to php. When I print out print(request.files.length); it gives me the file count which I choose for upload.
But in php side $countfiles = count($_FILES['file']); always returns 1.
why it could be?
Thanks for the answer #CBroe. It works. I added the recent codes down.
.dart
Future<http.Response> uploadFile(String fileName, List<int> fileBytes) async {
try {
var request = new http.MultipartRequest("POST", Uri.parse("https://****/***/fileupload.php"));
for (var i = 0; i < uploadedImage.length; i++) {
selectedFilesBytes = List.from(uploadedImage[i]);
request.files.add(http.MultipartFile.fromBytes('file[]', selectedFilesBytes, contentType: MediaType('application', 'octet-stream'), filename: files[i].name));
}
print("request.files.length");
print(request.files.length);
var streamedResponse = await request.send();
return await http.Response.fromStream(streamedResponse);
} catch (e) {
print(e);
}
.php
<?php
// Count total files
$countfiles = count($_FILES['file']['name']);
error_log($countfiles);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
}
?>

Move uploaded file fails after ajax request

I know this issue has been tackled a few times but no solution works for me,
I have a javascript function which pulls a file referenced by an which is as follows
function imagePreload(str)
{
var timestamp = new Date().getTime();
str = str + "&timestamp=" + timestamp;
var key = [];
var value = [];
var queriesarray = str.split('&');
for(i = 0; i < queriesarray.length; i++)
{
var pair = queriesarray[i].split('=');
key[i]= pair[0];
value[i]= pair[1];
}
for(i = 0; i < queriesarray.length; i++)
{
if (key[i]=="menu_id") {var menuid = value[i];}
if (key[i]=="menucategories_id") {var catid = value[i];}
}
for(i = 0; i < queriesarray.length; i++)
{
if (value[i]=="business") {var fileurlfield = "uploadbizimageid";}
if (value[i]=="category") {var fileurlfield = "uploadcatimageid" + catid;}
if (value[i]=="item") {var fileurlfield = "uploaditemimageid" + menuid;}
}
var fileInput = document.getElementById(fileurlfield);
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
}
reader.readAsDataURL(file);
} else {
alert("File not supported!");
}
document.getElementById("maskid").style.display = "block";
document.getElementById("imageuploadcontainerid").style.display = "block";
var filetosend = new FormData();
filetosend.append( 'image', file);
$.ajax({
url: "index.php?option=com_jumi&fileid=13&format=raw&" + encodeURI(str),
type: "POST",
data: filetosend,
processData: false,
contentType: false,
error: function (jqXHR, textStatus, errorThrown) {
alert("AJAX error: " + textStatus + ' : ' + errorThrown);
},
success: function(html) {alert("Orwight!");
document.getElementById('imageuploadcontainerid').innerHTML = html;
}
});
}
As you can see it is designed to make an AJAX call to a php file which is supposed to save that image file to a directory on the same webserver running the above function.
The php in that file looks like this.
$rest_id = $_GET['rest_id'];
$menu_id = $_GET['menu_id'];
$menucategories_id = $_GET['menucategories_id'];
$imagetype = $_GET['imagetype'];
if($imagetype=="business")
{
$db = &JFactory::getDBO();
$db->setQuery("SELECT * FROM g56s_restaurants WHERE rest_id = '$rest_id'");
$det = $db->loadObject();
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$target_path = "/images/restaurants/".$rest_id."/";
$target_path = $target_path ."businesslogo.".$ext."";
echo $target_path;
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
echo "The file ".basename( $_FILES['image']['name'])." has been uploaded";
} else {
echo "Not uploaded because of error #".$_FILES["file"]["error"];
}
}
Every time I call his script, the upload fails and no error is reported (i.e. no error number). A var dump shows that the the file error variable has a value of 0, and the file size is reported to be in the same order as that of the original file, and it has a tmp name. So in other words the file IS there in the TMP directory.
Directory permissions in the directory being written to are 777. There are no cross domain issues (and I guess no CORS issues) since the script is called from the same website (the PHP is actually in a JUMI application in a Joomla 3.4 website). However, the script ALWAYS fails to upload the file (the page returns "/images/restaurants/1/businesslogo.jpgNot uploaded because of error #." (since I also echoed the target_path before the error string echoed).
Does anyone know the reason for this and how to get the script to upload correctly ? I am completely stuck on this issue because as far as I can see, everything should work.
I solved the issue quicker than I thought, it turns out that I also have to specify the document root in the target path, so I amended
$target_path = "/images/restaurants/".$rest_id."/";
as
$target_path = $_SERVER['DOCUMENT_ROOT']."/images/restaurants/".$rest_id."/";
and it now works :-)

Receiving end of Cordova file upload

I'm working on uploading a file to a server using the cordova-file-transfer plugin. I know my file Upload works when using the browser to select a file yet I'm not entirely sure with the app since it's a relatively new way of doing it for me without form submissions.
EDIT: The below code is modified and is what was successful for me at the time after following #kay27's advice. The solution was to use params to POST the data to the awaiting upload handler.
function uploadFile() {
function success(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
/* Destination of file */
var url = encodeURI("http://someURL/yourPHPUploadFile.php");
var fileURI = "file:///storage/emulated/0/Android/data/com.yourPackageName/fileToUpload";
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "text/csv";
var params = new Object();
//allows you to POST the data to server side script
params.fileName = options.fileName;
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURI, url, success, fail, options);
}
The edited PHP form
<?php
header('Access-Control-Allow-Origin: *');
$location = "uploads/";
$uploadfile = $_POST['fileName'];
$uploadfilename = $_FILES['file']['tmp_name'];
if (move_uploaded_file($uploadfilename, $location . '/' . $uploadfile)) {
echo 'File successfully uploaded!';
} else {
echo 'Upload error!';
}
?>
For my particular issue, the newer way of defining the params worked. The solution can be seen here on Simon MacDonald's answer. I've edited the code above with the final solution that allowed me to upload.

Saving binary string to file in php sent from POST

I have a drag and drop uploader for (.jpg,.ai,.pdf,.flv,.psd ....etc.)
I'm reading the file as binary and sending the string in a jquery post:
function importZoneDrop(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
// files is a FileList of File objects. List some properties.
for (var i = 0, f; f = files[i]; i++) {
var start = 0;
var stop = files[0].size - 1;
var reader1 = new FileReader();
var reader2 = new FileReader();
var ext = f.name.substring(f.name.indexOf(".")+1);
if(ext == "JPEG" || ext == "jpeg" || ext == "JPG"){
ext ="jpg";
}
reader1.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
$("#import-drop-zone").append('<img src="'+e.target.result+'" />');
};
})(f);
reader2.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
$.post("/process/upload.php",{"blob":evt.target.result,"extension":ext},function(data){
console.log(data);
});
}
};
reader1.readAsDataURL(f);
var blob = f.slice(start, stop + 1);
reader2.readAsBinaryString(f);
}
}
This works and send the file. Next Get the string and write it using file_put_contents:
$extension = $_POST['extension'];
$file = $_POST['blob'];//sent from jquery post
$filePath = "../_temp/monkey.".$extension;
file_put_contents($filePath,$file);
if(file_put_contents($filePath,$file)){
echo json_encode("it worked");
}else{
echo json_encode("it failed");
}
This will successfully write the file. But the file does not work, it's broke.
What am I doing wrong?
You need to use base64_decode.
file_put_contents($filePath, base64_decode($file));
Note, you're currently writing the data twice. Don't.
if (file_put_contents($filePath, base64_decode($file))) {
is fine
Edit
Also worth nothing that it's more efficient to upload the binary file directly, then you can skip base64_decode. Something like this:
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append("file", f); // You don't need to use a FileReader
// append your post fields
// attach your events
xhr.addEventListener('load', function(e) {});
xhr.upload.addEventListener('progress', function(e) {});
xhr.open('POST', '/process/upload.php', true);
xhr.send(data);
You can view the rest of the events here with some samples here.

Categories