I am working through an old project and trying to fix a few bugs.
I have a file upload in HTML
function updateImage() {
circleArray = [];
newPic = `id="taco" width="300" height="300" src="${$(
"#myFile"
).val()}" alt="prime.png"`;
$("#hide").empty();
$("#hide").append(`<img ${newPic}>`);
makeCanvas();
}
<form>
<input type="file" id="myFile" name="filename">
<button id='submit'>Submit</button>
</form>
When I click the submit button I have a function that should update the image displayed with the newly uploaded image.
It seems like the file is uploaded but I am accessing it incorrectly.
I see the following error
GET c:\fakepath\IMG_0544.jpg net::ERR_UNKNOWN_URL_SCHEME
CodePudding user response:
I'm unable to reproduce the problem in your dynamic "code snippet", but it's pretty clear what's happening.
The error
GET c:\fakepath\IMG_0544.jpg net::ERR_UNKNOWN_URL_SCHEME
means that your browser was trying to access a file on your C:\ drive as though it were a remote URL. You can't do that :)ONE POSSIBLE SOLUTION: try uploading the image and rendering it as an "embeddd image", per this article:
https://www.thesitewizard.com/html-tutorial/embed-images-with-data-urls.shtml
ANOTHER POSSIBLE SOLUTION: Use FileReader.readAsDataURL():
https://www.tutorialrepublic.com/faq/how-to-preview-an-image-before-it-is-uploaded-using-jquery.php
CodePudding user response:
Try this :
function updateImage() {
circleArray = [];
newPic = `id="taco" width="300" height="300" src="${$("#myFile").get(0).files[0].name}" alt="prime.png"`;
$("#hide").empty();
$("#hide").append(`<img ${newPic}>`);
makeCanvas();
}
CodePudding user response:
Consider the following.
$(function() {
function updateImage() {
var newPic = $("<img>", {
id: "taco",
alt: "prime.png"
}).css({
width: 300,
height: 300
});
var myFile = $("#myFile")[0].files[0];
var reader = new FileReader();
reader.onload = function(event) {
newPic.attr("src", event.target.result);
$("#hide").empty().append(newPic);
};
reader.readAsDataURL(myFile);
//makeCanvas();
}
$("form").submit(function(event) {
event.preventDefault();
updateImage();
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="file" id="myFile" name="filename">
<button id='submit'>Submit</button>
</form>
<div id="hide"></div>
This reads the file from the input
element and renders it as an Image.