View image from storage in Laravel blade Repository pattern - laravel-9

image
I can upload my image to my storage In side public/images so I did this is my index.blade.php
<td><img src="public/images/{{ $row->image }}" width="100px"></td>
But it's not working
I just Want to show the image
Here Image
This is my userRepository.php
$name = $request->file('image')->getClientOriginalName();
$path = $request->file('image')->store('public/images');
$userStore->name = $name;
$userStore->path = $path;
$userStore->save();
return true;

Related

$Images not loaded properly on one product

I have an old version of prestashop (1.4) and facing issue with images for a new product. In my product.tpl, the $images Array is empty (count($images) = 0), so my thumbnails does not display.
// Images
var img_prod_dir = '{$img_prod_dir}';
var combinationImages = new Array();
{if isset($combinationImages)}
{foreach from=$combinationImages item='combination' key='combinationId' name='f_combinationImages'}
combinationImages[{$combinationId}] = new Array();
{foreach from=$combination item='image' name='f_combinationImage'}
combinationImages[{$combinationId}][{$smarty.foreach.f_combinationImage.index}] = {$image.id_image|intval};
{/foreach}
{/foreach}
{/if}
combinationImages[0] = new Array();
{if isset($images)}
//images : {$images} {count($images)}
{foreach from=$images item='image' name='f_defaultImages'}
//img - {$image.id_image}
combinationImages[0][{$smarty.foreach.f_defaultImages.index}] = {$image.id_image};
{/foreach}
{/if}
I checked in prestashop database and the structure seems OK, when I play SQL request found in product.php
return Db::getInstance()->ExecuteS('
SELECT i.`cover`, i.`id_image`, il.`legend`, i.`position`
FROM `'._DB_PREFIX_.'image` i
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
WHERE i.`id_product` = '.(int)($this->id).'
ORDER BY `position`');
the images are loaded properly for my product.
It seems that the link between the PHP and the TPL fails somewhere, but I don't know how to look deeper between those two elements. It only occurs on one product.
What I tested :
upload the image to another product --> it works
upload a working image on my failed product --> same behaviour
compare database content on ps_image, ps_product, and data seems to be the same
checked on the FTP if images are well generated --> OK
Do you have any idea where I can look further to check what fails with my product ?
Best regards
I finally found the issue, a previous developper made an override in the folder override/controllers/ProductController.php that causes, on some really specific case, a change of product ID and the images were not loaded.
git blame is fantastic :)

Uploading image using VF page and Apex to S3

I have tried creating Visualforce Page and Apex that sends the image to Amazon S3 bucket, Though it upload successfully but when i viewed the image using the link from Amazon it shows box instead of the actual image uploaded. See image below
Here is my Visualforce Code that sends the file to apex using javascript:
<input class="slds-input-custom" id="logo" name="bsLogo" type="file" />
<button id="submtBtn" onclick="toSubmit()" label="Submit" title="Submit" class="cSubmit" >Submit</button>
<apex:form id="formId">
<apex:actionFunction name="setParamAF" action="{!apexMethod}" rerender="panelId" status="checkingId" oncomplete="onloadCallback();">
<apex:param name="vBusiLogo" value=""/>
</apex:actionFunction>
</apex:form>
<script>
function toSubmit(){
reader.readAsDataURL(document.getElementById('logo').files[0]);
reader.onload = function(){
var dataURL = reader.result;
setParamAF(dataURL);
};
}
function onloadCallback(){
alert('uploaded');
}
</script>
The dataURL variable has these base64 value:
On the Apex class side, I have this code:
String busiLogo = '';
public static void apexMethod(){
busiLogo = ApexPages.currentPage().getParameters().get('vBusiLogo');
String logoName = 'image.png';
String bucketname ='amazon-file-s3';
String host = 's3-ap-sample-1.amazonaws.com';
Blob beforeblob = Blob.valueOf(busiLogo);
String attachmentBody = EncodingUtil.base64Encode(beforeblob);
HttpRequest req = new HttpRequest();
req.setMethod('PUT');
req.setEndpoint('callout:AmazonS3' + '/' + logoName);
req.setHeader('Host', bucketname + '.' + host);
req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
req.setHeader('Content-Encoding', 'UTF-8');
req.setHeader('Content-Type','image/png');
req.setHeader('Connection', 'keep-alive');
req.setHeader('Date', formattedDateString);
req.setHeader('ACL', 'public-read-write');
Blob blobFile = EncodingUtil.base64Decode(attachmentBody);
req.setBodyAsBlob(blobFile);
Http http = new Http();
HTTPResponse res = http.send(req);
}
Can you help me how will I send my actual image to s3 file, or where did I go wrong with my code?
I figured out that since the busiLogo variable is base64 encoded, I can just decode it and remove the "data:image/png;base64", from it. and then encode the value and send the encoded blob value to S3.

Image upload with selenium webdriver

Using selenium web driver with java. I have an image upload control using which i need to upload an image. I have tried .sendKeys method by passing image path that didn't work.
I have tried robot class, first clicks the button that opens a Window (windows native window) but it didn't type the keys in the "File Name" area.
<fieldset class="fieldset-company_logo post-fieldSet">
<label for="company_logo">Opportunity image:</label>
<div class="field">
<div class="upload-button">
<button class="button">Choose File</button>
<span>No file chosen</span>
<input class="input-text" name="company_logo" id="company_logo" placeholder="" type="file">
</div>
<small class="description"> Max. file size: 2MB. Allowed file format: jpg, gif, png </small>
</div>
</fieldset>
I got the solution for my question please review below details:
Function to set data to clip board, I will user this to set image path to clip board that I will user later on model window:
public static void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
Now review these lines of code
WebElement upload_btn = driver.findElement(By.xpath(choose_file_btn_xpath));
Thread.sleep(4000);
setClipboardData(selected_image_path);
Actions builder = new Actions(driver);
Action myAction = builder.click(upload_btn).release().build();
myAction.perform();
Robot rbt = new Robot();
rbt.delay(4000);
rbt.keyPress(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_V);
rbt.keyRelease(KeyEvent.VK_V);
rbt.keyRelease(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_ENTER);
rbt.keyRelease(KeyEvent.VK_ENTER);
rbt.delay(4000);
driver.findElement(By.xpath(submit_button_xpath)).click();
Thanks for your help and support.
Glad to hear that you found a way for uploading image. Just to share with you another way of doing this. At instance, if in single go you need to upload all images/files (one or more) sitting in a folder, you can use this script:
#Test
public void Upload() throws InterruptedException
{
File images = new File("*path where all images are saved*");
File[] eimages = images.listFiles();
String imageList = "";
for(int i = 0; i < eimages.length; i++){
imageList += (i != 0 ?"\n":"") + eimages[i].getAbsolutePath();
}
driver.findElement(By.id("fileupload")).sendKeys(fishList);
Thread.sleep(5000);
System.out.println("Images Uploaded");
}

Serve up images from network to View in ASP.NET MVC

I'm trying to load images from my server and then load them to a view:
var files = _directoryInfo.GetFiles()
.Where(x => x.Name.Contains(request.WarrantyReference))
.ToList();
model.Photos = files;
return View(model);
Then in the View im doing:
#if (Model.Photos.Count > 0)
{
#Html.Partial("_Photos", Model.Photos)
}
_Photos:
#model List<FileInfo>
<div class="ui items">
#foreach (var photo in Model)
{
<div class="item">
<div class="image">
<img src="#photo.FullName">
</div>
</div>
}
</div>
But nothing appears, I get the following error in the console:
Not allowed to load local resource:
file://my-server/dataphoto/WX0001 1.jpg
So I was wondering if it is possible to store the photos temporarily on my server to serve them to the View or is there another way around this?
Store the file names (or some identifier) in your Model.
Model
class Model
{
IList<string> Photos { get; set; }
Create an HtmlHelper to display your photo image.
In your example you could store "WX0001 1.jpg" as the photo identifier then when you read the file from the network server you look in a specific directory.
View
#model List<FileInfo>
<div class="ui items">
#foreach (var photo in Model)
{
<div class="item">
<div class="image">
#Html.PhotoImage(photo)
</div>
</div>
}
</div>
public static MvcHtmlString PhotoImage(this HtmlHelper html, string id)
{
var img = new TagBuilder("img");
var your_image_byte_array = read_image_from_server_using_id;
var base64 = Convert.ToBase64String(your_image_byte_array);
img.Attributes.Add("src", String.Format("data:image/gif;base64,{0}", base64));
return MvcHtmlString.Create(img.ToString());
}
Alternatively, have a look at using an Action method to display the image... Convert Byte Array to Image and Display in Razor View
you would need to copy the files somewhere where the ASP.NET user being used for the AppPool serving/hosting the website has access to. Alternatively, give the share the app pool account privileges to read. One other way would be to read the files and store them in a byte[] and finally render it on the screen/view without actually writing the files to disk.

I need help in uploading a file to a folder on my server and then adding the file details to a database

I am trying to make a page for my site where users can upload a game, give it a name then the file gets uploaded to a folder on my site and the file name and game name get added to my sql database but it gives an error saying: "System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index" when i try to run it.
My code for this page is:
#{
var db= Database.Open("Games");
var sqlQ = "SELECT * FROM Games";
var data = db.Query(sqlQ);
}
#{
var fileName = "";
if (IsPost) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
}
var GameName="";
var GameGenre="";
var GameYear="";
if(IsPost){
GameName=Request["formName"];
var SQLINSERT = "INSERT INTO Games (Name, file_path) VALUES (#0, #1)";
db.Execute(SQLINSERT, GameName, fileName);
Response.Redirect("default.cshtml");
}
}
<h1 >Add a new game to the database</h1>
<form action="" method="post">
<p>Name:<input type="text" name="formName" /></p>
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Add")
The error page says that the problem is with line 11 but i don't know what to change.
As Hightechrider has correctly said, your code should reside in Controllers, not in views. The exception you are getting is because Request.Files is an empty array, so when you're trying to access [0] element, you get an IndexWasOutOfRange error.
I'd recommend you reading the following article for uploading files in ASP.NET MVC. It presents an easier, more consistent and flexible model by putting the code in the controller action. Basically, all code boils down to this:
You create an upload form with submit button and file input.
You create an action that accepts HttpPostedFileBase variable.
You must set the proper enctype to your form if you want to upload files:
<form action="" method="post" enctype="multipart/form-data">