如何在JS中存储和显示上传的图像?

huangapple go评论74阅读模式
英文:

How to store and display uploaded image in JS?

问题

以下是您要翻译的内容:

const log = document.getElementById("log");
possibleIngredients.length = 0;
let uniqueIngredients = [];
const recipes = {};
const recipeAdder = document.getElementById('RecipeAdder');
const recipeName = document.getElementById('inputrecipetitle');
const searchButton = document.getElementById('searchbutton');
const threshold = 3
const compareButton = document.getElementById('submitknowningredients');


function addRecipe(title, input){ 
   const ingredients = Array.from(input).map(input => input.value);
   recipes[title] = ingredients;
}
//below is the levenshtein function, basically just allowing error in between search and title
function levenshtein(a, b) {
    const matrix = [];
  
    for (let i = 0; i <= b.length; i++) {
      matrix[i] = [i];
    }
  
    for (let j = 0; j <= a.length; j++) {
      matrix[0][j] = j;
    }
  
    for (let i = 1; i <= b.length; i++) {
      for (let j = 1; j <= a.length; j++) {
        if (b.charAt(i - 1) === a.charAt(j - 1)) {
          matrix[i][j] = matrix[i - 1][j - 1];
        } else {
          matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
        }
      }
    }
  
    return matrix[b.length][a.length];
  }



recipeAdder.addEventListener("submit", function(e){
   e.preventDefault();
   const input = document.querySelectorAll('.ingredients');
   const inputArray = Array from(input);
   const recipeLink = document.getElementById('recipelinksubmit');
   const image = document.getElementById('imageupload');
   document.body.style.backgroundImage = `url(${image})`;
   console.log(image);
   addRecipe(recipeName.value, inputArray);
    input.forEach(function(input){
    possibleIngredients.push(input.value);
    input.value = '';
    
});
 uniqueIngredients = [...new Set(possibleIngredients)];
});

searchButton.addEventListener("click", function(e){
    e.preventDefault();
    
    const recipeSearch = document.getElementById('recipesearch');
    for (const title in recipes){
        const normalizedSearch = recipeSearch.value.toLowerCase();
    const normalizedTitle = title.toLowerCase();
        const distance = levenshtein(normalizedSearch, normalizedTitle);
        if(distance <= threshold){
            console.log(recipes[title]);
        }
    }
})

compareButton.addEventListener('click', function(e){
    e.preventDefault();
    const ingredientsInput =  document.getElementById('myingredients');
    const myIngredients = ingredientsInput.value.split(',').map(ingredient => ingredient.trim().toLowerCase());
    for(const title in recipes){
        const recipeIngredients = recipes[title].map(ingredient => ingredient.toLowerCase());
        const isMatch = recipeIngredients.every(ingredient => myIngredients.includes(ingredient));

        if(isMatch){
            console.log(`you can make ${title} with your ingredients`);
        }
    }


})


log.addEventListener('click', function(){
    console.log(uniqueIngredients);
    for(const title in recipes){
        console.log(title, recipes[title]);
    }
    
});
<html lang=&quot;en&quot;&gt;
<head&gt;
    <link rel=&quot;stylesheet&quot; href=&quot;recipefinder.css&quot;&gt;
    <meta charset=&quot;UTF-8&quot;&gt;
    <meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE edge&quot;&gt;
    <meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    <title&gt;Recipe Finder&lt;/title&gt;
</head&gt;
<body&gt;
    <h1 class=&quot;scroll&quot;&gt;Possible Recipes&lt;/h1&gt;
    <h2 class=&quot;hadingredients&quot;&gt;Ingredients In Stock:&lt;/h2&gt;
    <div  class=&quot;possiblerecipes&quot;&gt;
       
        <img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic1&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic2&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/MangoCandy.jpg&quot; class=&quot;pic3&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/Meatballs.jpg&quot; class = &quot;pic4&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic5&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic6&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/MangoCandy.jpg&quot; class=&quot;pic7&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/Meatballs.jpg&quot; class = &quot;pic8&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic9&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
        <img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic10&quot;&gt;
        <a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;

<details>
<summary>英文:</summary>

I&#39;m pretty new to JS and HTML, and this is a very simple question, but I haven&#39;t found any straightforward solution. What I&#39;m trying to do is in the form submission, there is a file upload. When the form is submitted, I want to store the uploaded image in an object under the &quot;Recipe name&quot;, I can do all that, what I need help in is figuring out how to store uploaded images and then redisplay them as an image all on the html page.

In this code, I set image to the getelementbyid &quot;imageupload&quot; and just to test it out, when the button is pushed, it would set the background image to the url. I know just setting it equal to image shouldn&#39;t be the URL, but I&#39;ve tried image.value and image.src and a couple others, and none of them worked, so I just need to know how to get something like this to work.

const possibleIngredients = [];
const log = document.getElementById("log");
possibleIngredients.length = 0;
let uniqueIngredients = [];
const recipes = {};
const recipeAdder = document.getElementById('RecipeAdder');
const recipeName = document.getElementById('inputrecipetitle');
const searchButton = document.getElementById('searchbutton');
const threshold = 3
const compareButton = document.getElementById('submitknowningredients');

function addRecipe(title, input){
const ingredients = Array.from(input).map(input => input.value);
recipes[title] = ingredients;
}
//below is the levenshtein function, basically just allowing error in between search and title
function levenshtein(a, b) {
const matrix = [];

for (let i = 0; i &lt;= b.length; i++) {
  matrix[i] = [i];
}

for (let j = 0; j &lt;= a.length; j++) {
  matrix[0][j] = j;
}

for (let i = 1; i &lt;= b.length; i++) {
  for (let j = 1; j &lt;= a.length; j++) {
    if (b.charAt(i - 1) === a.charAt(j - 1)) {
      matrix[i][j] = matrix[i - 1][j - 1];
    } else {
      matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
    }
  }
}

return matrix[b.length][a.length];

}

recipeAdder.addEventListener("submit", function(e){
e.preventDefault();
const input = document.querySelectorAll('.ingredients');
const inputArray = Array.from(input);
const recipeLink = document.getElementById('recipelinksubmit');
const image = document.getElementById('imageupload');
document.body.style.backgroundImage = url(${image});
console.log(image);
addRecipe(recipeName.value, inputArray);
input.forEach(function(input){
possibleIngredients.push(input.value);
input.value = '';

});
uniqueIngredients = [...new Set(possibleIngredients)];
});

searchButton.addEventListener("click", function(e){
e.preventDefault();

const recipeSearch = document.getElementById(&#39;recipesearch&#39;);
for (const title in recipes){
    const normalizedSearch = recipeSearch.value.toLowerCase();
const normalizedTitle = title.toLowerCase();
    const distance = levenshtein(normalizedSearch, normalizedTitle);
    if(distance &lt;= threshold){
        console.log(recipes[title]);
    }
}

})

compareButton.addEventListener('click', function(e){
e.preventDefault();
const ingredientsInput = document.getElementById('myingredients');
const myIngredients = ingredientsInput.value.split(',').map(ingredient => ingredient.trim().toLowerCase());
for(const title in recipes){
const recipeIngredients = recipes[title].map(ingredient => ingredient.toLowerCase());
const isMatch = recipeIngredients.every(ingredient => myIngredients.includes(ingredient));

    if(isMatch){
        console.log(`you can make ${title} with your ingredients`);
    }
}

})

log.addEventListener('click', function(){
console.log(uniqueIngredients);
for(const title in recipes){
console.log(title, recipes[title]);
}

});


<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="recipefinder.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recipe Finder</title>
</head>
<body>
<h1 class="scroll">Possible Recipes</h1>
<h2 class="hadingredients">Ingredients In Stock:</h2>
<div class="possiblerecipes">

    &lt;img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic1&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic2&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/MangoCandy.jpg&quot; class=&quot;pic3&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/Meatballs.jpg&quot; class = &quot;pic4&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic5&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic6&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/MangoCandy.jpg&quot; class=&quot;pic7&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/Meatballs.jpg&quot; class = &quot;pic8&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic9&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic10&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/MangoCandy.jpg&quot; class=&quot;pic11&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/Meatballs.jpg&quot; class = &quot;pic12&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/brocolli_cheese.jpg&quot; class = &quot;pic13&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/GarlicBread.jpg&quot; class=&quot;pic14&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/MangoCandy.jpg&quot; class=&quot;pic15&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;
    &lt;img src=&quot;img/Meatballs.jpg&quot; class = &quot;pic16&quot;&gt;
    &lt;a class=&quot;init&quot; href=&quot;https://google.com&quot;&gt;Placeholder&lt;/a&gt;

&lt;/div&gt;
&lt;div class=&quot;hadingredientslist&quot;&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;✔️test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;❌test&lt;/p&gt;
    &lt;p class=&quot;hadingredient&quot;&gt;❌test&lt;/p&gt;





&lt;/div&gt;


&lt;form id=&quot;RecipeAdder&quot;&gt;
    &lt;label for=&quot;Enter your Recipe Name Here: &quot;&gt;Enter Your Recipe Name Here: &lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;inputrecipetitle&quot;&gt;&lt;br&gt;
    &lt;label for=&quot;Enter Your Ingredients Below:&quot;&gt;Enter Your Ingredients Below: &lt;/label&gt;&lt;br&gt;

    &lt;input type=&quot;text&quot; id=&quot;ingredientspace1&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace2&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace3&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace4&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace5&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace6&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace7&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace8&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace9&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;text&quot; id=&quot;ingredientspace10&quot; class=&quot;ingredients&quot;&gt;&lt;br&gt;
    &lt;label for=&quot;link&quot; &gt;Enter The Recipe Link Here: &lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;recipelinksubmit&quot; class=&quot;link&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;file&quot; id=&quot;imageupload&quot; class=&quot;file&quot;&gt;
    &lt;button type=&quot;submit&quot;&gt;Submit Recipe!&lt;/button&gt;
    
&lt;/form&gt;
&lt;input type=&quot;text&quot; id=&quot;recipesearch&quot;&gt;
&lt;button id=&quot;searchbutton&quot;&gt;Search Me&lt;/button&gt;

<br>
<input type="text" id="myingredients" placeholder="Enter Known Ingredients Here Seperated by a Comma"><br>
<button id="submitknowningredients">Look for Recipes!</button>

&lt;button id=&quot;log&quot;&gt;Log Me!&lt;/button&gt;
&lt;script src=&quot;recipefinder.js&quot;&gt;&lt;/script&gt;

</body>
</html>


</details>


# 答案1
**得分**: 1

以下是您要翻译的内容:

如果您只对设置容器元素的背景图像感兴趣(在这种情况下,文档主体),如上所述,您可能会发现以下简短的代码段有用。

您可以将事件监听器绑定到`file`输入字段,并处理对文件选择的任何更改。事件处理程序可以访问`files`属性 - 有关`File` API的信息,请参见[此处](https://developer.mozilla.org/en-US/docs/Web/API/File),有关在应用程序中使用此API的信息,请参见[此处](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications)。

有了对文件的引用,可以使用`FileReader` API来读取文件。 

成功读取文件后,`FileReader`实例将触发`load`事件,该事件触发一个回调函数,用于创建一个新的`Image`,然后将其用作所选容器的`backgroundImage`属性。

浏览本地系统上的图像文件以设置为背景图像。

<details>
<summary>英文:</summary>

If you are only interested in setting the background image of a container element ( in this case the document.body ) as seems the case given the wording of the above you might find the following short snippet of use.

You bind an event listener to the `file` input field and process any changes made to the selection of files. The event handler has access to the `files` property - see [`here`](https://developer.mozilla.org/en-US/docs/Web/API/File) for information about the `File` api and [`here`](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications) about using this in applications.
With a reference to the file the [`FileReader`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) api can be used to, funnily enough, read the file. 

Upon successfully reading a file the FileReader instance will fire a `load` event which triggers a callback function that is used to create a new `Image` which in turn is then used as the `backgroundImage` property for the chosen container.

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    document.querySelector(&#39;input[type=&quot;file&quot;]&#39;).addEventListener(&#39;change&#39;,e=&gt;{
      let file=e.target.files[0];
      let reader = new FileReader();
          reader.onload=function( evt ){
            let img=new Image();
                img.onload=( e )=&gt;{
                  document.body.style.backgroundImage=`url(${img.src})`;
                  
                  /* 
                  To obtain a &quot;storable&quot; string representation of the image
                  - write the image to a canvas and use `toDataURL` to get
                  the base64 encoded source data....
                  */
                  let canvas=document.querySelector(&#39;canvas&#39;);
                      canvas.width=img.width;
                      canvas.height=img.height;
                      
                  let ctxt=canvas.getContext(&#39;2d&#39;);
                      ctxt.drawImage( img, 0, 0 );
                  
                  let imgstr=canvas.toDataURL( file.type );
                  ctxt.clearRect(0,0,ctxt.canvas.width,ctxt.canvas.height);
                  
                  console.log( imgstr )
                }
            img.src = evt.target.result;
          };
          reader.readAsDataURL( file );
    });

&lt;!-- language: lang-css --&gt;

    canvas{display:none}

&lt;!-- language: lang-html --&gt;

    &lt;input type=&#39;file&#39; /&gt;
    &lt;canvas&gt;&lt;/canvas&gt;

&lt;!-- end snippet --&gt;


Browse for a image file on your local system to set as the background image.


</details>



huangapple
  • 本文由 发表于 2023年4月11日 05:10:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定