简体   繁体   English

从数组 60 多个选项中选择随机图像 javascript

[英]Picking random image from array 60+ choices javascript

I understand this question has tons of answers already, but I am trying to figure out how to do this in the most efficient way.我知道这个问题已经有很多答案了,但我正试图弄清楚如何以最有效的方式做到这一点。 I have a website that sends an image with a button click to a phone number, but I want to choose between 60 or so photos and manually entering all of these image locations into an array does not seem ideal.我有一个网站,可以通过单击按钮将图像发送到电话号码,但我想在 60 张左右的照片之间进行选择,并且手动将所有这些图像位置输入到数组中似乎并不理想。 Here is my js file that performs the email action, this is all hosted on a free hosting service.这是我执行 email 操作的 js 文件,它全部托管在免费托管服务上。

// server.js
const express = require("express")
const app = express()
app.use(express.static("public"))

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html") 
  /* this sends the "index.html" file when people go to app.glitch.me/ */
})

app.get("/send", (req, res) => {
// where node app starts
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.USER,
    pass: process.env.PASS,
  }
});

var mailOptions = {
  from: process.env.USER,
  to: process.env.RECIP,
  subject: "As you requested",
  text: '',
  attachments: [
    {
 /*image location*/
      path: 'https://post.healthline.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg',
    }
  ]
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
}); 

  res.redirect("/sent.html") // after sending the email, redirect back to "index.html" at app.glitch.me/
})
app.listen(3000); //open for traffic 

Here is my HTMl if its even relevant to my question这是我的 HTMl 如果它甚至与我的问题有关

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Hello!</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style_index.css">

     <a href="/send">click me for snazzy pics</a><!-- script to ping --!>

    <!-- import the webpage's javascript file -->
    <script src="/script.js" defer></script>
  </head>  
  <body>
    <h1>hello</h1>

    <p>
      I made this.
    </p>
  </body>
</html>

Try first logging all of your images from where they are hosted.尝试首先从托管它们的位置记录所有图像。 If it is not a database you can call upon then you may need to create an array of them manually.如果它不是您可以调用的数据库,那么您可能需要手动创建它们的数组。 Once they are in an object, you can simply use a variable to determine which position in the array that image link should come from.一旦它们位于 object 中,您可以简单地使用一个变量来确定图像链接应该来自数组中的哪个 position。 I hope the below helps.我希望下面的帮助。

For example:例如:


imageChoices = ["https://post.healthline.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg", "https://post.healthline.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg", etc.]

randomIndexChooser = Math.floor(Math.random() * 60) + 1;


var mailOptions = {
  from: process.env.USER,
  to: process.env.RECIP,
  subject: "As you requested",
  text: '',
  attachments: [
    {
 /*image location*/
      path: imageChoices[randomIndexChooser],
    }
  ]
};

you need to make an ajax service that calls an api, the api loops through all the files that are in the specified folder and returns the list of file paths.您需要创建一个调用 api 的 ajax 服务,api 循环遍历指定文件夹中的所有文件并返回文件路径列表。 after you get the list from the api, you append them to the wanted array in your javascript code.从 api 获得列表后,您将 append 将它们添加到 javascript 代码中的所需数组中。

I will provide you a sample in asp.net c#, you may be working on another framework, but you can benefit from the idea at least.我将在 asp.net c# 中为您提供一个示例,您可能正在使用另一个框架,但您至少可以从这个想法中受益。

here is a function in an api这是 api 中的 function

[HttpGet]
       public List<string> GetImageFilesPaths()
       {
//getfiles returns all found files' paths in a specified directory
           List<string> imageFilePaths = Directory.GetFiles("folderpath", "*.png", SearchOption.AllDirectories).ToList();
       }

ajax service that calls the API调用 API 的 ajax 服务

  $.ajax({
        url:'hostname/apiname/GetImageFilesPaths'
        contentType: "application/json",
        dataType: 'json',
        success: function(result){
            //here you append the result which is the list of file path
            //into your wanted array, you can also loop 
            result.forEach((imagePath)=>{
          arrayOfImages.push(imagePath)
          })

        }
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM