2016-12-26 28 views
3

我从来没有做过类似的事情,经过一段时间的调查,我没有找到我想要的东西。如果存在,我可能太愚蠢,无法注意/理解它。Node.js存储图像。在前端获取这些图像

管理方

在网站我发展(在管理页面),我有这只是一个简单的基于文本的形式,一种形式。我可以通过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); 

}); 

客户端: 图像被加载并放置在特定的地方。

回答

1

是的,你可以做到这一点。

以下是你需要使用multer具有以下CONFIGS(不要忘记身体的解析器)的例子

<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"); } }) });

在服务器端。所有这些之前的路线。

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 
}); 

希望这有助于。

+0

工作得很好。谢谢 – DigitalEvolution