The method create a zip file and download it.The file is created inside storage/app/public folder (I ran php artisan storage:link to create a symlinks) but it doesn't download.
public function download()
{
$zip_file = 'screenshots.zip';
$zip_path = storage_path('app/public/'.$zip_file);
$zip = new \ZipArchive();
$zip->open($zip_path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$path = storage_path('app/public/screenshots');
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file) {
if ($file->isDir()) {
continue;
}
$filePath = $file->getRealPath();
$relativePath = 'screenshots/' . substr($filePath, strlen($path) + 1);
$zip->addFile($filePath, $relativePath);
}
$zip->close();
return response()->download($zip_path);
}
JS
function downloadImages() {
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch('/download', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text-plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': token
},
method: 'get',
})
.then((response) => {
console.log('download');
})
.catch((error) => {
console.log(error);
})
}
For cross-platform download at client browser, You can use php echo string:
echo "Here is your download link: " . "<a id="photos_collection" href='". $zip_path ."' download='". $zip_file ."'>". $zip_file . " (" . filesize_formatted($zip_path) . ")" ."</a>";
Js
r is a div for receiving response as responseText:
$("#r").html(this.responseText); $("#photos_collection").click();
$("#r").html(response); $("#photos_collection").click();
Fixed! The APP_URL was not set correctly.
I also changed the JS method to:
function downloadImages() {
window.location = '/download';
}
Thanks #pathum-bandara
Related
I developed a PHP project, now I am working on connecting it to react native app. However, I tried many codes to upload image to the server nothing works.
Here is my code example,
const uploadImage = async () => {
// Check if any file is selected or not
if (singleFile != null) {
// If file selected then create FormData
const fileToUpload = singleFile;
const data = new FormData();
data.append('file_attachment', fileToUpload);
// Please change file upload URL
fetch(
'http://192.168.8.105/insaf/mobileConnection/upload.php',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
).then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson[0].Message == "Success") {
navigation.replace('ReqPriceList');
} else {
//setErrortext(responseJson.msg);
console.log('Please check');
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
} else {
// If no file selected the show alert
alert('Please Select File first');
}
};
And for the PHP server side (upload.php), here is the code
if(!empty($_FILES['file_attachment']['name']))
{
$target_dir = "../assets/files/request/";
if (!file_exists($target_dir))
{
mkdir($target_dir, 0777);
}
$target_file =
$target_dir . basename($_FILES["file_attachment"]["name"]);
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo json_encode(
array(
"status" => 0,
"data" => array()
,"msg" => "Sorry, file already exists."
)
);
die();
}
// Check file size
if ($_FILES["file_attachment"]["size"] > 50000000) {
echo json_encode(
array(
"status" => 0,
"data" => array(),
"msg" => "Sorry, your file is too large."
)
);
die();
}
if (
move_uploaded_file(
$_FILES["file_attachment"]["tmp_name"], $target_file
)
) {
echo json_encode(
array(
"status" => 1,
"data" => array(),
"msg" => "The file " .
basename( $_FILES["file_attachment"]["name"]) .
" has been uploaded."));
} else {
echo json_encode(
array(
"status" => 0,
"data" => array(),
"msg" => "Sorry, there was an error uploading your file."
)
);
}
}
I got this code from here https://aboutreact.com/file-uploading-in-react-native/
And I am getting
this error
Can anyone help me?
Any alternative solution will be fine.
Edit:
based on #Sadia Chaudhary code this function works
let uploadImage = async () => {
//Check if any file is selected or not
if (singleFile != null) {
//If file selected then create FormData
const fileToUpload = singleFile;
console.log("fileToUpload is " + fileToUpload);
const uriPart = fileToUpload[0].uri;
const fileExtension = fileToUpload[0].name.split('.')[1];
console.log("fileExtension is " + fileExtension);
const data = new FormData();
//const uriPart = fileToUpload.split('.');
//const fileExtension = uriPart[uriPart.length - 1];
data.append('file_attachment', {
uri: uriPart,
name: `photo.${fileExtension}`,
type: `image/${fileExtension}`
});
let res = await fetch(
'http://myIp/insaf/mobileConnection/uploads.php',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
);
let responseJson = await res.json();
if (responseJson.status == 1) {
alert('Upload Successful');
}
} else {
//if no file selected the show alert
alert('Please Select File first');
}
};
The error has nothing to do with the image upload. You are facing this error because of response.json(). Also, try to convert image like this.
//retrive the file extension of your photo uri
const uriPart = imageSource.split('.');
const fileExtension = uriPart[uriPart.length - 1];
formData.append('photo', {
uri: imageSource,
name: `photo.${fileExtension}`,
type: `image/${fileExtension}`
});
I need to download multiple files with Guzzle using concurrent requests so i choose to use Pool.
Basically, I wrote a function that receives a list of URL that are the remote files i need to download and a path which is the directory where i want to save the files.
The function should save in the provided directory each file I'm sending the request to but instead the directory reamins empty and no file as been wrote inside it.
What am I doing wrong?
Here is my function with some echos for debugging purpose:
function async_multiple_files_download($files_url_list, $path) {
$client = new \GuzzleHttp\Client();
$requests = array();
for ($i = 0; $i < sizeof($files_url_list); $i++) {
$file_name = basename($files_url_list[$i]);
$request_destination_file_path = $path . DIRECTORY_SEPARATOR . $file_name;
$requests[$i] = new GuzzleHttp\Psr7\Request('GET', $files_url_list[$i], ['sink' => $request_destination_file_path]);
echo "Downloading " . basename($files_url_list[$i]) . "<br>from($files_url_list[$i])<br>to $request_destination_file_path" . "<br><br><br>";
}
$pool = new \GuzzleHttp\Pool($client, $requests, [
'concurrency' => 10,
'fulfilled' => function (\Psr\Http\Message\ResponseInterface $response, $index) {
echo 'success: '.$response->getStatusCode()."<br>";
},
'rejected' => function ($reason, $index) {
echo 'failed: '.$reason."<br>";
},
]);
$promise = $pool->promise();
$promise->wait();
}
I have code that sends an image to my server and everything works fine. However i am now truing to send a file to my server using an input tag in ionic However i cant seem to get it working.
I get an error from the php file saying undefined index 'file'
HTML
<ion-col>
<ion-label>Add a File</ion-label>
<ion-input type='file' [(ngModel)]="fileName"></ion-input>
</ion-col>
TS file
addFile() {
this.addService.addFile(this.fileName).subscribe(res => {
console.log(res);
});
}
service
addFile(file) {
let headers = new HttpHeaders();
// headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Authorization', '' + this.token);
const formData = new FormData();
formData.append('file', file);
return this.http.post<any>('http://domain.fileUpload.php', formData, {headers});
}
PHP API
$target_path = "files/";
$target_path = $target_path . basename( $_FILES['file']['name']);
$findDate = date("Y-m-d");
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
header('Content-type: application/json');
$data = ['success' => true, 'message' => 'Upload and move success'];
echo json_encode( $data );
} else {
header('Content-type: application/json');
$data = ['success' => false, 'message' => 'There was an error uploading the file (folder), please try again!'];
echo json_encode( $data );
}
uploadMethod
uploadFile: ''; // from ngModel
fileUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'file',
fileName: '.png',
chunkedMode: false,
};
console.log(this.uploadFile);
fileTransfer
.upload(this.uploadFile, 'http://domain/fileUpload.php',
options
)
.then(
data => {
console.log(data + 'Uploaded Successfully');
// console.log(JSON.parse(data.));
// let res = JSON.parse(data);
let res = data;
if (res['success']) {
console.log('True');
}
},
err => {
console.log(err);
}
);
}
Blow is the Example Code:
import { Platform } from 'ionic-angular';
checkPlatform: boolean = fasle;
constructor(public plt: Platform) {
if (this.plt.is('ios')) {
this.checkPlatform == true; // if platform ios this will be true
}
if (this.plt.is('android')) {
this.checkPlatform == true; // if platform androidthis will be true
}
}
imageUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'image',
fileName: '.png',
chunkedMode: false,
//mimeType: "image/jpeg",
}
fileTransfer.upload(path, 'https://yourDomain.com/api/imageUpload', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
console.log(JSON.parse(data.response));
let res = JSON.parse(data.response);
if (res.success == true) {
// do whats ever you want to do
}
}, (err) => {
console.log(err);
});
}
Pass the cordova file path as parameter in this function.
inside you HTML template show buttons or input type like this:
<input type="file" *ngIf="checkPlatform == true">
if you see this you can notice allowed types are :
export type TextFieldTypes = 'date' | 'email' | 'number' | 'password' | 'search' | 'tel' | 'text' | 'url' | 'time';
if you want to upload files follow this link i think you will find the answer
I check your code and as i see file added to FormData is filename with string Type, not File or Blob Data Type. So in this case it will not send file into $_FILES, it actually send its value to $_POST in your PHP Server. In summary, File and Blob Type will be sent to $_FILES, other data types will be sent to the appropriate global variables.
There is also a good example on how to validate your file in PHP Server: https://www.php.net/manual/en/features.file-upload.php
I'm trying to upload images through TinyMCE but am getting "HTTP Error: 403" shown in the editor itself. I've taken the code from the website for both the script and the php page respectively:
tinymce.init({
selector: "textarea",
plugins: "link image",
height:300,
setup: function (editor) {
editor.on('change', function () {editor.save();});
},
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'queries/editorImageUpload.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
And then within 'editorImageUpload.php', I think the problem is to do with the $accepted_origins part as its returning a 403 error:
$accepted_origins = array("https://localhost", "https://77.104.172.194");
$imageFolder = "pictures/Test/";
reset ($_FILES);
$temp = current($_FILES);
if (is_uploaded_file($temp['tmp_name'])){
if (isset($_SERVER['HTTP_ORIGIN'])) {
// same-origin requests won't set an origin. If the origin is set, it must be valid.
if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
} else {
header("HTTP/1.1 403 Origin Denied");
return;
}
}
Any insight on this would be very helpful.
First of all you have two problems with your code
-your php code does not transfer the image to the server
-in your php code you are making array of $accepted_origins with "https://localhost" and you forget the unsecured version "http://localhost"
so the fastest fix for your problem is to write valid php code that will transfer the image to your server and return the image full path for the editor here is the php code
editorImageUpload.php
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'images';
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$file_name = substr(md5(rand(1, 213213212)), 1, 5) . "_" . str_replace(array('\'', '"', ' ', '`'), '_', $_FILES['file']['name']);
$targetFile = $targetPath. $file_name;
if(move_uploaded_file($tempFile,$targetFile)){
die( $_SERVER['HTTP_REFERER']. $storeFolder . "/" . $file_name );
}else{
die('Fail');
}
}
?>
and in your javascript callback you have to check for the xhr.response not the xhr.responseText since you are dying with the image full path
Tinymce code
tinymce.init({
selector: "textarea",
plugins: "link image",
height:300,
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'editorImageUpload.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
console.log(xhr.response);
//your validation with the responce goes here
success(xhr.response);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
I am trying to upload files using angular2 and PHP server. The variable $_FILES is empty and I cannot figure out the reason.
Component code:
let formData:FormData = new FormData();
for (let i = 0; i < this.filmsFiles.length; i++) {
formData.append('images', this.filmsFiles[i], this.filmsFiles[i].name);
}
this.filmDataService.uploadFiles(formData).subscribe( outPutData => {
if(outPutData[0]){...
Service Angular code:
uploadFiles(formData:FormData): Observable {
this.data = 'action=10060&jsonData=""';
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data; charset=utf-8; boundary=' + Math.random().toString().substr(2));
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post(this.url+'?'+this.data, formData, options)
.map((response:Response) => response.json())
.catch(this.handleError)
}
PHP code:
foreach($_FILES['images']['error'] as $key => $error){
if($error == UPLOAD_ERR_OK){
$name = $_FILES['images']['name'][$key];
$fileNameParts = explode(".", $name);
$nameWithoutExtension = $fileNameParts[0];
$extension = end($fileNameParts);
$newFileName = "film_".$i.time().".".$extension;
move_uploaded_file($_FILES['images']['tmp_name'][$key], '../../images/' . $newFileName);
$newFileNames[]='images/filmsImages/'.$newFileName;
$i++;
}
I've been checking whether the variable this.filmsFiles is empty or not and it contains the files to upload, in the view, file tag, I have:
(change)="filmsFiles[i]=$event.target.files[0]"
The server receives the parameters I send but nothing in $_FILES.
Could you help me please?
Thanks,
Roberto