I have a file saved in storage/app/uploads and I would like get this this image saved and show with img src tag.
But I can't
I am trying:
public function getSlider(Request $request)
{
$slider = Slider::find( $request->input('id') );
$slider->imagem = storage_path('storage/app/uploads/'.$slider->imagem);
return response()->json( $slider );
}
And I am trying show with jquery and javascript
function getSliders() {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN' : $('#token').val() }
})
$.ajax({
url: "{{ route('site.getSlider') }}",
type: "post",
dataType: "json",
data: {
id: $('#id').val()
}
}).done( r => {
console.log('r',r)
$('#description').val( r.description )
setImage( r.image )
})
}
And setting Image
function setImage( image ){
var newImage = document.createElement('img');
newImage.setAttribute('src', image);
newImage.width = 500;
newImage.heigth = 200;
document.getElementById("photo").innerHTML = newImage.outerHTML;
}
When I want access image from public/img I use
<img src="{{ URL('img/myImage.png') }}">
But I want to access from storage/app/uploads
This return the file route (no url) (if you see the log it says /var/www.... etc)
storage_path('storage/app/uploads/'.$slider->imagem);
You should use asset helper to create URL of image
asset( 'storage/app/uploads/'.$slider->imagem);
Before this you need to run this command to create symbolic link to storage folder from public folder.
php artisan storage:link
Please try this and let me know how it works :)
try save your images in public folder instead of storage
its simple you can access it by using public_path() function.
Firstly, run this command:
php artisan storage:link
Then in any view you can access your image with the help of url helper.
url('storage/app/uploads');
Related
I am currently implementing a pdf export functionality within a wordpress plugin i'm developing but the pdf file generated when i click on export button is empty. To implement the export i use FPDF library
Ive put the code which uses FPDF in a function which is executed by the wp_ajax_ action hook. Here is the code:
<?php
require_once plugin_dir_path( __FILE__ ) . 'fpdf/fpdf.php';
function pdf_pull_wpse_212972() {
$pdf = new FPDF('p','mm','a4');
$pdf->SetFont('arial','b',14);
$pdf->AddPage();
$pdf->Cell(40,10,'Referrer URL',1,0,'C');
$pdf->Cell(40,10,'User IP Address',1,0,'C');
$pdf->Cell(40,10,'User Agent',1,0,'C');
$pdf->Cell(40,10,'Browser',1,0,'C');
$pdf->Cell(40,10,'OS',1,0,'C');
$pdf->Output();
wp_die();
}
add_action('wp_ajax_pdf_pull','pdf_pull_wpse_212972');
Here is the jQuery code executed when i click on the export button
jQuery(document).ready(function($) {
jQuery('#pdf-export-btn').click(function(){
var data = {
'action': 'pdf_pull',
};
jQuery.post(tclisecure.ajax_url, data, function(response) {
var downloadLink = document.createElement("a");
var fileData = [response];
var blobObject = new Blob(fileData,{
type: "application/pdf"
});
var url = URL.createObjectURL(blobObject);
downloadLink.href = url;
downloadLink.download = "tracked_info.pdf";
/*
* Actually download PDF
*/
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
});
});
I'm trying to upload images from a Vue frontend via Illuminate/Http/Request to WinterCMS.
Vue finds the file and i can console.log the File object, but I'm unsure how to get this over the api. for example I've tried
public function saveImage(Request $req){
$images = $req->files('images');
}
which doesn't work, nor does
public function saveImage(Request $req){
$images = $req['images'];
}
I'm using a controller to handle my routes eg:
Route::post('/saveImage', 'Author\Project\Controllers\ProductControl#saveImage');
I've added an attachOne relation to the plugin as usual and my form has enctype="multipart/form-data"
I've had this problem before and got around it by converting images to base64 but this project will have quite a few images and I don't want to go down that route again.
Any suggestions greatly appreciated
You can send images as regular post and use regular $request->file('images') method in your Laravel controller.
You can use Javascript FormData object. For example;
<div>
<input type="file" #change="handleImages" multiple>
<button #click="uploadImages">Upload!</button>
</div>
data: () => ({
images: []
}),
methods: {
handleImages (event) {
this.images = event.target.files
},
uploadImages () {
const formData = new FormData();
for (const i of Object.keys(this.images)) {
formData.append('images', this.images[i])
}
axios.post('/saveImage', formData, {
}).then((res) => {
console.log(res)
})
}
}
First of all, this is the start of where I am at as a similar post
Store blob as a file in S3 with Laravel
I am sending a photo from VueJS to Laravel. It is coming as multipart/form-data.
Vue Code:
export default {
emits: ['onClose'],
props: ['isOpen'],
data: function() {
return {
serverOptions: {
process: (fieldName, file, metadata, load, error) => {
const formData = new FormData();
formData.append(fieldName, file, file.name);
axios({
method: "POST",
url: '/chat/room/upload',
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
load();
})
.catch(() => {
error();
});
}
},
files: [],
};
},
methods: {
handleFilePondInit: function () {
console.log('FilePond has initialized');
// example of instance method call on pond reference
this.$refs.pond.getFiles();
console.log(this.$refs.pond.getFiles());
},
},
Laravel Controller:
public function uploadImage(Request $request)
{
// This is what this is SUPPOSED to do. Grab the file from the frontend
// Bring it here. Store it in S3, return the path with the CDN URL
// Then store that URL into the DB as a message. Once that is done, then
// Broadcast the message to said room.
if ($request->has('upload')) {
$files = $request->get('photo');
$urls = [];
foreach ($files as $file) {
$filename = 'files/' . $file['name'];
// Upload File to s3
Storage::disk('digitalocean')->put($filename, $file['blob']);
Storage::disk('digitalocean')->setVisibility($filename, 'public');
$url = Storage::disk('digitalocean')->url($filename);
$urls[] = $url;
}
return response()->json(['urls' => $urls]);
}
// broadcast(new NewChatMessage($newMessage))->toOthers();
// return $newMessage;
}
First: I want to state that if there is something wrong with the current code, just know its because ive been playing around with this for 3 hours now and been trying anything. I am sure at one point I had it close but somehow screwed it up along the way so I am more looking for fresh eyes to show me my error.
That being said, the other part to take into account is in DevTools under Network I can clearly see the blob and can load it up, I can also see the "upload" item and under there the form data which shows the following
------WebKitFormBoundary7qD7xdmiQO9U1Ko0
Content-Disposition: form-data; name="photo"; filename="6A8B48B4-F546-438E-852E-C24340525C20_1_201_a.jpeg"
Content-Type: image/jpeg
------WebKitFormBoundary7qD7xdmiQO9U1Ko0--
it clearly also shows photo: (binary) so I am completely confused as to what I am doing wrong. The ULTIMATE goal here is to get the image, store it as public in S3/DigitalOcean then grab the public URL to the file and store in the DB.
Any help would be GREATLY appreciated!
I'll like to implemente the image upload system within my Laravel/VueJS project but I can't find a right way to do so. How can I set up my Controller function in order to handle this upload?
Edit:
This is my Editor configuration:
config: {
imageUploadParam: 'imageFile',
imageUploadURL: '/froala/upload/image',
imageUploadMethod: 'POST',
imageMaxSize: 5 * 1024 * 1024,
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
}
And this is the function that handles the request:
public function uploadImage(Request $request)
{
$file = $request['imageFile'];
$name = $file->getClientOriginalName();
$name = strtolower(str_replace(' ', '', $name));
$path = $file->hashName();
$image = Image::make($file);
Storage::put("/threads/{$path}", (string) $image->encode());
$multimedia = Multimedia::create([
'name' => $name,
'path' => $path
]);
return ['link' => $multimedia->path];
}
I am using the Intervention Image library to handle the image upload.
Edit 2:
I'm getting an 419 error related with the csrf token. So, how can i pass it to the function? I know how to get it but using the imageUploadParams configuration of the editor is not working:
imageUploadParams: {
csrf: this.csrf
}
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
You need to pass the correct X-CSRF-TOKEN value to avoid the 419 error.
First check that you have the token defined the in the meta header with something like:
<meta name="csrf-token" content="{{ csrf_token() }}">
Early in your VueJS add:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
Then add the following to your Froala config section:
config: {
requestHeaders: {
'X-CSRF-TOKEN': csrf_token
},
Media files should now pass through to your media upload function in Laravel.
From the documentation :
When an image is inserted into the WYSIWYG HTML editor, a HTTP request is automatically done to the server.
The specific URL that the request will be made to can be specified using the imageUploadURL config option.
Setup your routes.php file to properly direct the request to your controller of choice :
Route::post('/upload', 'FilesController#store');
Then, in your controller you can handle the image upload like you would normally. The important part is that you return the path to the file after you've saved it.
The returned JSON needs to look like: { "link": "path/to/image.jpg" }
Here is an example of what that could look like :
public function store(){
$filepath = request()->file('file')->store('images', 'public');
return ['link' => $filepath];
}
Of course, feel free to do any kind of validation or processing that you need.
instand of
imageUploadParams: {
csrf: this.csrf
}
use this
imageUploadParams: {
_token: this.csrf
}
Check this out From Documentation
I’m trying to require an image downloaded with react-native-fetch-blob in my Image component, but when I give it the image path it keeps saying me « Unknow named module: ‘/Users/…/Library/…’
What is the right way to require images stored in a local directory ?
let imagePath = null
RNFetchBlob
.config({
fileCache : true
})
.fetch('GET', uri)
// the image is now dowloaded to device's storage
.then((resp) => {
// the image path you can use it directly with Image component
imagePath = resp.path()
this.setState({ uri: require(imagePath) })
try {
AsyncStorage.setItem(`${this.props.uri}`, imagePath);
} catch (error) {
console.log(error)
}
})
My render method :
render() {
return(
<Image style={this.props.style} source={this.state.uri} />
)
}
The problem is not because I set a variable as source because it's working when I put something like : this.setState({ uri: require('../images/test.jpg') }) after my download.
require(imagePath) exists to help packager to find local images and place them to application bundle.
When you need to show dynamically loaded image, you simple need to pass file location as URI, for ex:
render() {
const imageAbsolutePath = this.state.imagePath;
const imageUri = 'file://' + imageAbsolutePath;
return <Image source={{uri: imageUri}}/>;
}
So, you shold not need any require statements in this case.