如何使用ejs进行图像选择和表达? [英] How to make an image selection with ejs and express?

查看:29
本文介绍了如何使用ejs进行图像选择和表达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node,express,moongoDB和EJS创建具有自定义帖子管理系统的博客站点.一切正常,但是我现在尝试使用mongoDB上Cloudinary上载的图像将多个图像添加到上载/编辑页面上的帖子中.从理论上讲,它非常简单,因为我只需要将图像ID或URL附加到所选的帖子文档中即可,但是在页面上选择哪个帖子和哪些图像会让我头疼.我正在努力与此配合使用前端JS和EJS,因为选择需要在前端进行并通过html表单发布到后端,我假设使用一个包含我的图像选择的数组.我的代码创建了一个名为"imageSelection"的数组来存储用户使用JS拾取的图像,然后尝试对它进行JSON字符串化并将其发布到服务器以进行处理.

我能够使用JS将图像保存在一个数组中,并可以使用foreach循环浏览数据库中的图像以使用EJS显示选项.然后,我只能弄清楚如何发布静态数据,但是这对我需要的方式不起作用,因为我想在对它进行字符串化后发布图像选择数组.我似乎无法使用普通JS来对存储在香草JS数组中的数据进行字符串化和发布,因为我需要调用一个函数,然后将数据插入提交的值中.我不确定这是我的代码唯一的问题.

我有所选图像的预览,该预览应该显示,但是我无法使用以前的代码,因为它可与EJS一起使用,并且需要与普通JS一起使用才能访问我的"imageSelection"数组.

 < form action ="/post-add-imgs" method ="post">< div class ="dropdown">< button class ="btn btn-primary" type ="button" data-toggle =下拉菜单">选择一个帖子< span class ="caret"></span></button>< ul class ="dropdown-menu hover_img"><%posts.forEach(function(post){%>< li>< a href =#"><%= post.title%></a></li><%});%></ul></div>< div class ="uploads-gallery"><%images.forEach(function(image){%>< a href =#" onclick ="addImage(<%= image.url%>));">< img src =<%= image.url%>"alt =预览图片"height ="100"/></a><%});%></div>< input type ="hidden" name ="imageSelection" value ="json.stringify(imageSelection);">< button type ="submit" name ="button">添加图像选择</button></form> 

是否可以使用ejs显示选定的图像,然后将它们发布到json.stringify之后?我需要使用ajax来完成此操作吗?

感谢所有帮助和明智的话语.

解决方案

我不太确定我理解您的问题,但是让我们看看我是否可以帮助我解决我认为的问题.我认为您需要能够选择一些通过.ejs文件渲染的图像,通过客户端JS将图像的url存储在一个数组中,然后在POST请求中将该数组发送到Express服务器.

使用您的代码为基础,我将按照以下方式进行操作:

客户端

我创建了一个.ejs文件,该文件渲染了Express服务器在图像"局部变量中发送的一些图像:

 < div id ="image-container"><%images.forEach((image)=> {%>< a href =#">< img src =<%= image.url%>"></a><%})%></div>< button id ="add-image-button">添加图像选择</button> 

然后,我有一个.js文件,该文件使用包裹图像的< div> 上的事件侦听器将单击的图像添加到"imageSelection"数组中:

  const imageContainer = document.getElementById('image-container');const imageSelection = [];imageContainer.addEventListener('click',(e)=> {如果(!imageSelection.includes(e.target.src)){imageSelection.push(e.target.src);}}); 

最后,当用户单击添加图像选择"按钮时,图像选择"数组中的图像通过获取请求发送到端点"

I am using node, express, moongoDB, and EJS to make a blog site with a custom post management system. That all works well, but I am now trying to use Cloudinary uploaded images from my mongoDB to add multiple images to posts on an upload/edit page. In theory it works very simply, as I just need to append image IDs or URLs to a chosen post document.But selecting which post, and which images on one page is giving me headaches. I'm struggling to use front-end JS and EJS in harmony with this as the selection needs to be made on the front end and posted to the back-end through the html form, I assume with an array that includes my image selections. My code makes an array called 'imageSelection' to store the images picked by the user with JS, and then it attempts to JSON stringify and POST the array to the server for processing.

I was able to save the images in an array with JS, and to use a foreach to cycle through the ones from my database to display the options with EJS. I can then only figure out how to POST static data but that doesn't work in the way I need it to since I want to post the image selection array after stringifying it. I seem to be unable to use plain JS to stringify and post the data I store in my array in vanilla JS because I need to call a function and then insert the data into the submitted value. I'm not sure this is the only problem with my code here though.

I have a preview of the chosen images, which should display but I can't use my former code because it works with EJS, and it needs to work with plain JS to access my 'imageSelection' array.

    <form action="/post-add-imgs" method="post">
  <div class="dropdown">
    <button class="btn btn-primary" type="button" data-toggle="dropdown">Select a Post
    <span class="caret"></span></button>
    <ul class="dropdown-menu  hover_img">
      <%  posts.forEach(function(post){ %>
        <li><a href="#"><%=post.title%></a></li>
        <% }); %>
    </ul>
    </div>

  <div class="uploads-gallery">
    <%  images.forEach(function(image){ %>
      <a href="#" onclick=" addImage(<%=image.url%>); "><img src="<%=image.url%>" alt="preview image" 
  height="100" /></a>
      <% }); %>
  </div>

  <input type="hidden" name=" imageSelection " value="json.stringify(imageSelection);">
  <button type="submit" name="button">Add image choice</button>
  </form>

Is there a way to use ejs to display the selected images, and then to post them on after a json.stringify? Will I need to use ajax to accomplish this?

Thanks for all help, and wise words.

解决方案

I'm not quite sure I understand your question, but let's see if I can help with what I think I know. I think you need to be able to select some images that are rendered via an .ejs file, store the image url's in an array via client-side JS, then send that array in a POST request to an Express server.

Here's how I would do that, using your code as a basis:

Client Side

I created an .ejs file that rendered some images that my Express server sent across in an 'images' local variable:

<div id="image-container">
  <% images.forEach((image) => { %>
     <a href="#"><img src="<%= image.url %>"></a>
  <% }) %>
</div>

<button id="add-image-button">Add Image Choice</button>

Then, I have a .js file that adds images that are clicked to an 'imageSelection' array using an event listener on the <div> that wraps the images:

const imageContainer = document.getElementById('image-container');
const imageSelection = [];

imageContainer.addEventListener('click', (e) => {
  if (!imageSelection.includes(e.target.src)) {
    imageSelection.push(e.target.src);
  }
});

And finally, when the user clicks the 'Add Image Choice' button, the images in the 'imageSelection' array are sent via a fetch request to the endpoint 'http://localhost:3001/post-images'. The addImageButton has an eventListener attached to it that listens for the 'click' event, so you don't need a <form> element:

const addImageButton = document.getElementById('add-image-button');

addImageButton.addEventListener('click', async () => {
  const url = 'http://localhost:3001/post-images';
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(imageSelection)
  });
  const myJson = await response.json();
  console.log(JSON.stringify(myJson));
});

Server-Side

On the Express side, I have a route handler setup for the POST /post-images request that simply sends back the POST-ed data to the requester:

router.post('/post-images', (req, res, next) => {
  res.json(req.body);
});

So, for your purposes, this pattern allows the user to select images and then click a button and the url's of those images are sent to the server. If that's not what you're looking for, clarify and I will try and help.

It's currently Saturday, 11-16-2019 at 9:34 pm GMT as I'm editing this, and I'm leaving the house and won't be able to assist for another 20 hours or so, so don't expect a response before 5:30 pm GMT on Sunday, 11-17-2019.

I pushed my code up to a git repo here, just follow the instructions in the README and you should be able to test it out on your machine. The files you want to check out for this example specifically are:

  • views/index.ejs
  • public/javascripts/main.js
  • routes/index.js

Here's an image of the front-end, with the response logged after selecting the first two images:

这篇关于如何使用ejs进行图像选择和表达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆