Cannot upload an image to S3 Bucket - laravel

I am trying to upload an image to Amazon s3 bucket using vue js and laravel. But when i upload it the following exception appears :-
here's what i wrote in my controller to upload the file.
public function addProperty(Request $request)
{
$property = new Property;
$property->title = request('title');
$property->property_type = request('type');
$property->property_sub_type = request('subtype');
$property->address = request('address');
$property->property_index = 400;
#$property->save();
if ($request->hasFile('image')) {
$fileNameWithExtension = $request->file('image')- >getClientOriginalName();
$fileName = pathinfo($fileNameWithExtension, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore =$fileName.'_'.time().'_'.'.'.$extension;
$disk = Storage::disk('s3');
$disk->put($fileNameStore, fopen($request->file('image'), 'r+'), 'public');
$profilePicImageUri = Storage::disk('s3')->url($fileNameStore);
dd($profilePicImageUri);
return $profilePicImageUri;
}
}
here's what i have done in Vue
onSubmit(){
let self = this;
let data = new FormData();
data.append('image',this.file);
data.append('title',this.propertyTitle);
data.append('type',this.type);
data.append('subtype',this.subtype);
data.append('lat',this.lat);
data.append('long',this.long);
data.append('address',this.address);
let config = {
headers:{
'Content-Type' : 'multipart/form-data'
}
}
axios.post(baseUrl + "api/admin/addproperty",data,config)
.then(function (response) {
console.log(response);
}).catch(function (error) {
{
console.log(error);
}
})
},
I have already setup my aws Configuration in env file. Here's my configuration
AWS_ACCESS_KEY_ID=XXXX
AWS_SECRET_ACCESS_KEY=XXX
AWS_DEFAULT_REGION=eu-central-1
AWS_BUCKET= php-laravel-upload
AWS_URL = https://php-laravel-upload.s3.eu-central-1.amazonaws.com
I don't understand what i am doing wrong. Can anyone help me?

try like that
if ($request->hasFile('image')) {
$fileInstance = $request->file('image');
$fileNameStore = $fileInstance->getClientOriginalName().'_'.time().'_.'.$fileInstance->getClientOriginalExtension();
Storage::disk('s3')->put($fileNameStore, $fileInstance, 'public');
$profilePicImageUri = Storage::disk('s3')->url($fileNameStore);
// dd($profilePicImageUri);
return $profilePicImageUri;
}

Related

upload multiple image in flutter app to a laravel api

Here is my function in flutter
I have use multi_image_picker to pick images sand i have save them in that variable images. Now I want post those images in laravel api. But this don't work.
if(images != null ){
try{
List<MultipartFile> allMultiFiles = [];
for (Asset asset in images) {
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
print(imageData);
var multipartFile = new MultipartFile.fromBytes(
imageData,
filename: asset.name,
);
allMultiFiles.add(multipartFile);
}
FormData formData = FormData.fromMap({
'images' : allMultiFiles
});
var response = await dio.post(UPLOAD_URL, data:formData);
if(response.statusCode == 200){
print('done');
}else{
print('not save image. Error !!');
}
}catch (e){
print(e.toString());
}
}
}
Here is my function to store
public function save(Request $request){
if(!$request->hasFile('images')){
return response()->json([
'upload file not found' => 'not found'
],400);
}else{
$allowedExtension = ['jpg','jpeg','png'];
$files = $request->file('images');
$erros = [];
foreach ($files as $file){
$extension = $file->getClientOriginalExtension();
$check = in_array($extension,$allowedExtension);
if($check) {
foreach($request->images as $mediaFiles) {
$path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
return response()->json([
'message' => 'images saved'
],200);
}
} else {
return response()->json(['invalid_file_format'], 422);
}
}
}
}
It not work, images are not saved.
I'm beginner in flutter and thanks for your help.

How can i insert multiple images Laravel / VUE / Axios

How can i upload multiple images instead of one, uploading one image works now this is what i am using. I have uploaded many images with Laravel and blade, but with vue im not sure on how to achieve this
Vue Template
<input type="file" v-on:change="onImageChange" multiple />
In Vue Script
onImageChange(e) {
// console.log(e.target.files[0]);
this.image = e.target.files[0];
},
SubmitProducts(e) {
e.preventDefault();
const config = {
headers: { "content-type": "multipart/form-data" },
};
let formData = new FormData();
formData.append("image", this.image);
axios
.post("/admin/products", formData, config)
.then((result) => {
var v = this;
v.showalert = true;
setTimeout(function () {
v.showalert = false;
}, 3000);
})
.catch((err) => {
console.log(err);
});
},
ProductController
public function store(Request $request)
{
DB::beginTransaction();
try {
$image = $request->file('image');
$fileName = 'products' . time() . '.' . $image->getClientOriginalExtension();
Storage::disk('uploads')->put($fileName, file_get_contents($image));
$product->image = $fileName;
$product->save();
DB::commit();
return response()->json('Product successfully inserted');
}

How to get files as url from laravel storage folder and convert them as base 64 in vuejs?

i'm trying to get files from storage folder and converting them into base64 in vue.js. i'm using below method, But it seems not working.
public function getImages()
{
$filesToReturn = [];
$files = File::files(storage_path() . "/app/record_keeper");
foreach ($files as $file) {
array_push($filesToReturn, $file->getRealPath());
}
return response()->json(['files' => $filesToReturn], $this->response_status_code, 200);
}
returned file urls
{"files":["/home/Project/vue_image_previewer/storage/app/record_keeper/1.jpeg","/home/Project/vue_image_previewer/storage/app/record_keeper/2.jpeg"]}
in vue js
data() {
return {
imageUrls: [],
images: [],
img_id: 0,
currentIndex: 0,
savedImages: [],
}
},
methods: {
async getAllImagesById() {
await this.axios.get('/aaa-get-images').then(response => {
this.savedImages = response.data.data;
self.savedImages.forEach(function (url) {
this.toDataUrl(url);
});
},
toDataUrl(url) {
let self = this;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
self.imageUrls.push({
file: reader.result,
});
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
}
where is the problem?
Thank you!
here is the result.
You are getting the relative path of the image file. XMLHttpRequest cannot read the image like that. You should return the image URL like http://somedomain.com/storage/image.jpg from the laravel getImages() method.
i fixed it my own. had to change both backend and frontend.
fileSystem.php
'my_folder' => [
'driver' => 'local',
'root' => storage_path('app/public/uploads/my_folder')
],
controller method
public function getImages()
{
$filesToReturn = [];
$files = File::files(storage_path() . "/app/public/uploads/my_folder");
foreach ($files as $file) {
$fileName = basename($file);
$file = Storage::url('uploads/my_folder/' . $fileName);
array_push($filesToReturn, url($file));
}
return $this->apiResponse(['files' => $filesToReturn], $this->response_status_code, 200);
}
frontend method
async convertUploadedFilesToBase64(savedImages) {
let self = this;
for (let i = 0; i < savedImages.length; i++) {
fetch(savedImages[i])
.then(res => res.blob())
.then(blob => {
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
let base64String = reader.result;
self.imageUrls.push({
file: base64String,
});
console.log('Base64 String - ', base64String);
console.log('Base64 String without Tags- ', base64String.substr(base64String.indexOf(', ') + 1));
}
});
}
},

Download txt file with laravel and axios

Hello there
Hope you will be doing good.I want to download txt file generated on the fly from the controller of laravel i have search alot but could not find any solution.Please help out i will be very thankful.
Blade code with axios request
submitHandler:function(form,e){
var btn=document.querySelector("#BtnSubmit");
btn.style.display="none";var img=document.createElement("img");
img.setAttribute("src",base_url+'front/images/loading.gif');
var loader=document.querySelector("#loader");loader.appendChild(img);
var url="<?php echo route('database.export-txtProcess');?>";
var cur_url="<?php echo route('database.export-txt');?>";
//var tblExportSelect = $("#tblExportSelect").val();
var pushArray = [];
$.each($("#tblExportSelect option:selected"), function(){
pushArray.push($(this).data("id"));
});
var data = new FormData();
data.append('tblExportSelect',pushArray);
//$("#tblExportSelect").val(selected);
axios({
method: 'POST',
url: url,
data: data,
})
.then(function(res){
console.log(res);
})
e.preventDefault();
}
});
Controller Method
public function exportTxtProcess(Request $request){
/*dd($request->tblExportSelect);*/
$tables = explode(",", $request->tblExportSelect);
$destinationPath = public_path('/');
$result;
foreach ($tables as $table) {
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table."-".$today;
$fp = fopen($destinationPath . "$fileName.txt","wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table,$output);
fwrite($fp,$netResult);
}
$result = fclose($fp);
}
/*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
echo json_encode($arr);*/
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$downloaded = response()->download($pathToFile)->deleteFileAfterSend();
}
}
I want to download when txt file which is created as above but instead of download it streaming in the console.
Thank in advance
You have to pass the headers. Most importantly you are not returning the reponse.
$headers = [
'Content-type' => 'text/plain',
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Length' => sizeof($content)
];
return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();

Problem uploading images with Axios and Laravel

I'm trying to upload and save images with Axios and a Laravel API, but i'm getting a 422 error.
I've tested with Postman and i have the same result, i have a similar controller**(without the Foreach)** but to upload only one image at once and it works fine.
///Axios
async submitFiles(){
let fd = new FormData()
for(var i = 0; i < this.files.length; i++){
let file = this.files[i]
fd.append('photo[' + i + ']', file)
}
try{
await this.$axios.$post(`/albums/${this.$route.params.id}/photos`, fd, {headers:{'Content-Type': 'multipart/form-data'}})
console.log(...fd)
alert('uploaded')
this.files = []
}
catch(err){
console.log(err)
alert(err)
}
}
//Laravel
class PhotosInAlbumController extends Controller
{
public function store(PhotoInAlbumRequest $request, Album $album)
{
if($request->hasfile('photo'))
{
$photo = new PhotoInAlbum();
$photo->photo = $request->photo;
$images[] = $request->file('photo');
foreach ($images as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathInfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('photo/images', $filenameToStore,'public');
$photo->photo = $path;
$album->photos()->save($photo);
}
}
return $photo;
}
}
Hope someone can help me to figure out what's going on.
Thanks in advance (=
First, sorry I can't comment yet. But I see in this line:
$images[] = $request->file('photo');
that a bi-dimensional array is built. I would try the assignment without the brackets:
$images = $request->file('photo');

Resources