node mongoose
Are you building a full-stack app and want to let users upload an image but you’re not sure how? In my experience, this is always achieved by having users input a link and saving this string to your database. This works great and is quick and easy, but it’s also kind of cheating. What kind of app makes you first go to another site and upload your image, and then come back and link to it?
您是否要构建一个全栈应用程序,并想让用户上传图像,但不确定如何? 以我的经验,这总是通过让用户输入链接并将此字符串保存到数据库中来实现的。 这很好用,快速又容易,但也有种作弊行为。 什么样的应用程序使您首先转到另一个网站并上传图片,然后返回并链接到该网站?
So, what’s the solution?
那么,解决方案是什么?
Allow the user to input a file, then on your server, upload this file to a cloud service and save this in your database. Cloudinary is great for this. It’s dedicated to media uploads. It has great documentation. It allows for transformations. And has a huge free plan (10 GB storage). You can sign up for Cloudinary here (I get nothing for this).
允许用户输入文件,然后在您的服务器上将此文件上传到云服务并将其保存在数据库中。 Cloudinary对此非常有用。 它专用于媒体上传。 它具有出色的文档。 它允许进行转换。 并具有庞大的免费计划(10 GB存储空间)。 您可以在此处注册Cloudinary (对此我一无所获)。
<form action='/api/images' method="post" enctype="multipart/form-data">
<input type='file' name='image' />
</form>
This should look familiar. All you need is a form which will submit the information to the server. Enctype is required for submitting files to the server.
这看起来应该很熟悉。 您所需要做的就是将信息提交到服务器的表格。 必须使用Enctype才能将文件提交到服务器。
That’s the front-end solved.
那就是前端解决了。
Now, the back-end is where all the magic happens. You will need all the usual dependencies for working with Express and Mongoose. In addition, we will utilise Multer, Cloudinary, and multer-storage-cloudinary. Multer will allow access to files submitted through the form. Cloudinary is used for configuration and uploading. multer-storage-cloudinary will make the process of combining these easy.
现在,后端就是所有魔术发生的地方。 您将需要使用Express和Mongoose的所有常规依赖项。 另外,我们将利用Multer , Cloudinary和multer-storage-cloudinary 。 Multer将允许访问通过表单提交的文件。 Cloudinary用于配置和上传。 multer-storage-cloudinary将使组合这些过程变得容易。
const multer = require("multer");
const cloudinary = require("cloudinary");
const cloudinaryStorage = require("multer-storage-cloudinary");
Once the dependencies are required you need to configure them. When you sign up to Cloudinary, you will be provided your API credentials. I recommend storing these in a “.env” file to keep them secure.
一旦需要依赖项,就需要对其进行配置。 注册Cloudinary时,将为您提供API凭据。 我建议将它们存储在“ .env”文件中,以确保它们的安全。
Below we are also:
下面我们也是:
There’s a lot more you can do in regards to transformations — you can take a look here if you are interested.
关于转换,您可以做更多的事情-如果您有兴趣,可以在这里看看。
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
});
const storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: "demo",
allowedFormats: ["jpg", "png"],
transformation: [{ width: 500, height: 500, crop: "limit" }]
});
const parser = multer({ storage: storage });
Now that your server is all set up to receive and process these images, we can move onto setting up the route.
现在,您的服务器都已设置为可以接收和处理这些图像,接下来我们可以继续设置路由。
In your post route, you simply add the parser we set up before as a middleware. This will take in the file, upload it to Cloudinary, and return an object with the file information. You can access this information in the request object.
在您的发布路线中,您只需将我们之前设置的解析器添加为中间件即可。 这将接收文件,将其上传到Cloudinary,然后返回带有文件信息的对象。 您可以在请求对象中访问此信息。
I like to extract just the information I want from this, to keep my database organised. At the least, you will want:
我喜欢从中提取我想要的信息,以使数据库井井有条。 至少,您将需要:
app.post('/api/images', parser.single("image"), (req, res) => {
console.log(req.file) // to see what is returned to you
const image = {};
image.url = req.file.url;
image.id = req.file.public_id;
Image.create(image) // save image information in database
.then(newImage => res.json(newImage))
.catch(err => console.log(err));
});
Your image will probably be part of a larger object in your database. The image URL and id can be saved as strings as a part of this.
您的图像可能是数据库中较大对象的一部分。 图片网址和ID可以另存为字符串。
*Image is an example placeholder for your database collection. Substitute it for your own.
*图像是数据库集合的示例占位符。 自己替换它。
When you want to display the image on the front-end, perform a database query, and then use the URL inside your image tags <img src=imageURL
/>.
如果要在前端显示图像,请执行数据库查询,然后使用图像标签<img src=imageURL
/>中的URL。
I hope this will help you in adding that little extra to your websites. It’s not that difficult once you break down each step in the process. It will give your website the professional touch and will make it stand out.
我希望这会帮助您在网站上添加一些额外的内容。 分解流程中的每个步骤并不难。 这将使您的网站具有专业的风格,并使其脱颖而出。
If you have any questions, please ask in the comments.
如有任何疑问,请在评论中提问。
node mongoose