** How to get laravel Storage path in js file**
I want to display dinamic image in laravel from database using jquery ajax, but I can't get Stoage path in js file to put my image name
which is a variable:
images.forEach(function (image) {
var img = `<img src="http://localhost/storage/${product.image}"`;
});
"http://localhost/storage/" works,but I want to replace "http://localhost/storage/" to dinamic url using javascript
Use a relative path, which will fix the issue in any server.
As follows
images.forEach(function (image) {
var img = `<img src="/storage/${product.image}"`;
});
To get laravel storage path in js file you can do like:
In your headerfile.blade.php
<script>
var storagePath = {!! storage_path() !!}; // old with error
var storagePath = "{!! storage_path() !!}"; // updated and tested
</script>
The in js file you can use storagePath variable.
I hope this will help you.
For that either 1.
{!! storage_path('app/public') !!}
2.you can pass it with your data of product
or
3.you use model for set the full src of image
protected $appends = ['image_url'];
public function getImageUrlAttribute()
{
$imageUrl = "";
if (isset($this->attributes['image']) && $this->attributes['image'] != "") {
$imageUrl = storage_path('app/public').$this->attributes['image'];
}
return $imageUrl;
}
and you can use them in your blade like
images.forEach(function (image) {
var img = `<img src="${product.image_url}"`;
});
Related
This is my html code. Here I declared one variable.
<script src="index.js">
var str = {{:stringVar:}};
</script>
This is my JavaScript file content. Here if my condition satisfies my HTML file variable have to get my javascript file variable and it must be replaced.
var hello='gettingvalue from browser'
if(hello ='master'){
var changestr ='new asp key for mas';
}
else{
var changestr ='new asp key for dev'
}
How can I get my HTML file variable into js file?
you can use ajax to read your HTML file.
first read your HTML file then replace your new variable then write it into html file
Here I gave code to read html file inside JS file and replace that variable
if(true){
var aspkey = 'key for master';
var ajax = new ej.base.Ajax('./src/template.html', 'GET', true);
ajax.send().then(function (result) {
var f = result;
var newstr = f.replace(/{{:stringVar:}}/, aspkey)
});
}
else{
var aspkey = 'key for dev';
var ajax = new ej.base.Ajax('./src/template.html', 'GET', true);
ajax.send().then(function (result) {
var f = result;
var newstr = f.replace(/{{:stringVar:}}/, aspkey)
});
}
Finally you have to write this into your HTML file
You could get HTML file content using jquery ajax call as follows
$.get("PATH_TO_HTML_FILE", function(fileText){
console.log(fileText)
});
I have this line in my Razor :
#Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html")))
And in HTML file, I have this :
<li>Personal Records</li>
And in my js file I have this :
if ($(link).text() === 'Personal Records') {
$("#govde").load("PersonalRecords.html");
}
But when I click on that link, nothing happens. When I open Index.html directly from file browser, it works. How can I fix this?
EDIT :
In console, it has this :
http://localhost:12345/PersonalRecords.html 404 (Not Found)
I guess I have placed the html files to a wrong folder. Can you tell me where to place? Thanks.
EDIT2 :
I have this in my JS :
var upperMenu = document.getElementById('upperMenu');
var requests = document.getElementById('requests');
$(upperMenu ).click(function (event) {
ustMenu.childNodes.forEach((myList) => {
$(myList).attr('class', ' ');
});
var link = event.target;
var list = link.parentNode;
$(myList).attr('class', 'active');
if ($(link).text() === 'Personal Records') {
$("#govde").load('#Url.Content("~/PersonalRecords.html")');
}
});
.load function is created in this(seperate) JS file.
The problem started with file name mentioned in $("#govde").load method:
$("#govde").load("PersonalRecords.html");
This statement tries to load "PersonalRecords.html" which assumed exists in the project's root directory, but it returns 404 since the target file exist in different directory.
Hence, it should be mentions full absolute path URL to load HTML content first:
var url = '#Url.Content("~/Views/Home/PersonalRecords.html")';
Then, since load method placed inside separate JS file, putting them together should results like this:
Razor
<script src="#Url.Content("~/[path_to_your_JS_file]")" type="text/javascript"></script>
<script>
var url = '#Url.Content("~/Views/Home/PersonalRecords.html")';
loadRequest(url);
</script>
JavaScript file
function loadRequest(url) {
var upperMenu = $("#upperMenu").get(0);
var requests = $("#requests").get(0);
$(upperMenu).click(function (event) {
ustMenu.childNodes.forEach((myList) => {
$(myList).attr('class', ' ');
});
var link = event.target;
var list = link.parentNode;
$(myList).attr('class', 'active');
if ($(link).text() === 'Personal Records') {
$("#govde").load(url);
}
}
}
Next, as of first mentioned part:
#Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html")))
I considered this is not a good practice to read all file contents in view side, hence I prefer return the file contents from controller side using FilePathResult like #Guruprasad Rao said:
// taken from /a/20871997 (Selman Genç)
[ChildActionOnly]
public ActionResult GetHtmlFile(String path)
{
// other stuff
// consider using Server.MapPath(path) if in doubt determining file path
return new FilePathResult(path, "text/html");
}
Usage as link in view:
<li>#Html.ActionLink("HTML File", "GetHtmlFile", "Controller", new { path = "~/Views/Home/PersonalRecords.html" }, null)</li>
Similar issues:
Rendering .html files as views in ASP.NET MVC
Render HTML file in ASP.NET MVC view?
I have a MVC app that Im trying to use CKEditor with. One example I was looking at is here but there are many others. So far so good, but one section im still curious about, is the js that sends the selected file name back to the file upload dialog textbox.
<script type="text/javascript">
$(document).ready(function () {
$(".returnImage").click("click", function (e) {
var urlImage = $(this).attr("data-url");
window.opener.updateValue("cke_72_textInput", urlImage);
window.close();
});
});
</script>
In particular, the cke_72_textInput element. My example wasnt working initially, until I opened chrome dev tools and found the actual id of the textinput, which was in my case cke_76_textInput. Why the id change I wonder? Seems a little "fragile" to refer to a specific id like this? The above js code just takes the selected image file and returns it into the textbox of the fileupload dialog.
Is there something exposed that references this textbox element indirectly without specifying it by id (via the config for example)?
On view:
$(document).ready(function () {
CKEDITOR.replace('Text-area-name', {
filebrowserImageUploadUrl: '/Controller-name/UploadImage'
});
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here. For example:
config.language = 'de';
// config.extraPlugins = 'my_own_plugin'; // if you have any plugin
// config.uiColor = '#AADC6E';
// config.image_previewText = CKEDITOR.tools.repeat(' Hier steht dann dein guter Text. ', 8 );
// config.contentsLanguage = 'de';
config.height = 350; // 350px, specify if you want a larger height of the editor
config.linkShowAdvancedTab = false;
config.linkShowTargetTab = false;
};
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
ev.data.definition.resizable = CKEDITOR.DIALOG_RESIZE_NONE;
if (dialogName == 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('advanced');
}
if (dialogName == 'image') {
dialogDefinition.removeContents('Link');
dialogDefinition.removeContents('advanced');
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('txtBorder');
infoTab.remove('txtHSpace');
infoTab.remove('txtVSpace');
infoTab.remove('cmbAlign');
}
});
}
On Contoller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
{
if (file.ContentLength <= 0)
return null;
// here logic to upload image
// and get file path of the image
const string uploadFolder = "Assets/img/";
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(string.Format("~/{0}", uploadFolder)), fileName);
file.SaveAs(path);
var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
uploadFolder, fileName);
// passing message success/failure
const string message = "Image was saved correctly";
// since it is an ajax request it requires this string
var output = string.Format(
"<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
CKEditorFuncNum, url, message);
return Content(output);
}
I had the same problem...a little frustrating that I couldn't find any official documentation, considering this seems like a common use case.
Anyways, take a look at the quick tutorial here: http://r2d2.cc/2010/11/03/file-and-image-upload-with-asp-net-mvc2-with-ckeditor-wysiwyg-rich-text-editor/. In case the link ever breaks, here's what I did.
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase upload, string ckEditorFuncNum)
{
/*
add logic to upload and save image here
*/
var path = "~/Path/To/image.jpg"; // Logical relative path to uploaded image
var url = string.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Url.Content(path)); // URL path to uploaded image
var message = "Saved!"; // Optional
var output = string.Format("<script>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}');</script>",
CKEditorFuncNum,
url,
message);
return Content(output);
}
I am trying to use javascript to change an image in my blade file
but am getting the following error. As a side note I have enabled HTML forms in laravel, and I am able to display images without javascript.
Fatal error: Class 'HTML' not found (View:/home/vagrant/Code/Laravel/resources/views/pages/progress.blade.php)
Below is my javascript code
<script>
window.onload = function() {
changeImageForSeniorLevel();
};
function changeImageForSeniorLevel() {
var level = '<?php echo $levelValue; ?>';
if (level == 3)
{
document.getElementById("image").src="{{ HTML::image('progress2/Icons/Calls_Icon.png', 'alt',array('width' => 150 )) }}";
}
}
</script>
Here is the code for the image I am trying to change, the code will display an image if I comment my javascript.
{{ HTML::image('progress2/Icons/Meetings_Icon.png', 'alt', array('id' => 'image', 'width' =>150)) }}
HTML::image is a Laravel class / method that is parsed in PHP (which is hosted on your server). You cannot parse it using a browser / HTML. The browser does not know what HTML::image means. In your case, you just want to change the attributes of an image already drawn on your document.
You can use the following to achieve what you are looking for:
if(level == 3){
var myImage = document.getElementById("image");
myImage.src = 'progress2/Icons/Calls_Icon.png';
myImage.alt = 'alt';
myImage.style.width = '150px';
}
I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server