簡體   English   中英

從數組 60 多個選項中選擇隨機圖像 javascript

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

我知道這個問題已經有很多答案了,但我正試圖弄清楚如何以最有效的方式做到這一點。 我有一個網站,可以通過單擊按鈕將圖像發送到電話號碼,但我想在 60 張左右的照片之間進行選擇,並且手動將所有這些圖像位置輸入到數組中似乎並不理想。 這是我執行 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 

這是我的 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>

嘗試首先從托管它們的位置記錄所有圖像。 如果它不是您可以調用的數據庫,那么您可能需要手動創建它們的數組。 一旦它們位於 object 中,您可以簡單地使用一個變量來確定圖像鏈接應該來自數組中的哪個 position。 我希望下面的幫助。

例如:


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],
    }
  ]
};

您需要創建一個調用 api 的 ajax 服務,api 循環遍歷指定文件夾中的所有文件並返回文件路徑列表。 從 api 獲得列表后,您將 append 將它們添加到 javascript 代碼中的所需數組中。

我將在 asp.net c# 中為您提供一個示例,您可能正在使用另一個框架,但您至少可以從這個想法中受益。

這是 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();
       }

調用 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