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');
}
Related
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));
}
});
}
},
I have a script that should update a user's post without rebooting. But the form data, for some reason, is not transferred through the formData object, everywhere is null, except for those fields that are manually registered in the controller (id, user_id). What can be wrong?
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "PATCH",
data: formData,
success: function(data) {
console.log(data);
$("#textpostdata"+id).html($(data).find("#textpostdata"+id).html());
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
contentType: false,
processData: false,
});
});
And my controller
public function editPost(storeRequest $request, $id, $postId) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/' . Auth::user()->id . '/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
//return redirect()->back();
return $post;
}
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();
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;
}
Somehow it just doesnt upload the image to the folder. It goes so far as adding to the database (what model is all about) however no upload.
I hope to know what im doing rong. See my code bellow
The
HTML
<div class="dropzone infile dz-clickable" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" id="file" type="file" multiple />
</div>
</div>
JS
var myDropzone = new Dropzone("#my-dropzone", {
url: admin_url+'add_image/material',
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sending",function(file, xhr, formData){
file.token = Math.random().toString(36).substr(2,9);
formData.append("token",file.token);
formData.append("type", file.type);
formData.append("size", file.size);
});
this.on("complete", function (file) {
console.log(file);
});
this.on("successmultiple", function(file, response) {
console.log(file);
});
this.on("errormultiple", function(file, response) {
console.log(file);
});
this.on("removedfile",function(file){
var token = file.token;
$.ajax({
type:"post",
data:{token:token},
url: admin_url+'remove_image',
cache:false,
dataType: 'json',
success: function(res){
}
});
});
},
dictDefaultMessage: "<div class='drag-icon-cph'><i class='material-icons'>touch_app</i></div><h5>Plaats hier bestanden om te uploaden</h5>",
dictRemoveFile : "Bestand verwijderen"
});
PHP (Codeigniter)
public function add_image($type, $rel_id = 0){
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
$path = getcwd() . '/uploads/';
$tmpFilePath = $_FILES['file']['tmp_name'];
if (!empty($tmpFilePath) && $tmpFilePath != '') {
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
$extension = strtolower($extension);
$allowed_extensions = array(
'jpg',
'jpeg',
'png'
);
if (!in_array($extension, $allowed_extensions)) {
set_alert('warning', 'PHP blocked file extention');
return false;
}
$filename = uniqid(rand(), true).'.'.$extension;
$newFilePath = $path . '/' . $filename;
// Upload the file into the upload dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $newFilePath;
$config['new_image'] = $filename;
$config['maintain_ratio'] = true;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
$CI->image_lib->resize();
$CI->image_lib->clear();
$data = array(
'rel_type' => $type,
'rel_id' => $rel_id,
'attachment_key' => $this->input->post('token'),
'file_name' => $filename,
'filetype' => $this->input->post('type'),
'size' => $this->input->post('size'),
'dateadded' => date('Y-m-d H:i:s')
);
$id = $this->back_model->add_image($data);
if($id != ''){
array_push($_SESSION['tmp_image'],$id);
}
unlink($newFilePath);
}
}
}
}
The folder uploads is created and for security i added a empty index.html file.
.htaccess is standard Codeigniter