【问题标题】:Node.js store images. Get those images in front-endNode.js 存储图像。在前端获取这些图像
【发布时间】:2017-05-11 03:35:14
【问题描述】:

我从来没有做过类似的事情,经过一段时间的调查,我没有找到我想要的东西。如果存在的话,我可能太愚蠢了,无法注意到/理解它。

管理方面

在我正在开发的网站中(在管理页面中),我有一个表单,它只是一个简单的基于文本的表单。我可以通过 ajax 将表单信息发送到服务器。我现在需要发送我上传的图像文件。我想知道我是否可以在同一个呼叫中同时发送文本信息和图像(仅一种形式)?如果是,如何? (以下是我的 ajax 配置的一部分)。我还通过其 id 获取表单信息。

$.ajax({
    url: 'http://localhost:8080'+url,
    type: type,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(object),
    success: callback     
}

服务器端

当它只是文本时,我收到了“req.body”中的信息。我相信我应该收到带有“req.files”的文件。为此,我听说过Multer。但是,我不明白,我怎么能在同一个“app.post”中接收这两个信息。如果可能的话,这就是我想要的。我假设所有这些是将管理页面中的图像存储在非公共服务器文件夹中,然后在首页检索客户端要访问的所有图像。 (与此相关:存储在私人文件夹中并从那里检索它们是最佳解决方案并将路径存储在数据库中吗?)

类似的东西:

 // receive images and text 
 app.post("/admin_info",function(req,res) {

   var text_info = req.body;
   (...take care of text_info ...)

   var image_file = req.file;
   var images = "/images";
   // then save image_file in images and also save the image path in database to access it later

 });

 // retrieve specific images
 app.get('/', function (req,res) {

    var images = ["/images/img1.jpg","/images/img2.jpg",...];

    // get actual image files 

    res.send(image_files);

 });

客户端: 图像已加载并放置在特定位置。

【问题讨论】:

    标签: javascript ajax node.js server


    【解决方案1】:

    是的,你可以这样做。

    这是一个例子

    <form id="test" enctype="multipart/form-data"> <input type="text" name="name" ><br> <input type="file" name="poster" id="poster" multiple><br> <input type="submit" value="POST"> </form>

    JS代码

    $("#test").on('submit', function(e){ e.preventDefault(); var form_data = new FormData(this); $.ajax({ type: 'post', url: '/test/all', data: form_data, cache: false, contentType: false, processData: false, success: function(answ){ console.log("Done"); } }) });

    在服务器端,您需要使用具有以下配置的 multer(不要忘记正文解析器)。所有这些都在路由之前。

    const multer = require('multer');

    app.use(multer({ dest: './temp/'}).any());

    而不是你这样做的路线

    app.post("/test/all", function(req,res){
        console.log(req.body); //has name property
        console.log(req.files); //has all files that you upload
        //now just read files array and save files where you want
    });
    

    希望这会有所帮助。

    【讨论】:

    • 工作得很好。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多