【问题标题】:Upload directory doesn't send folder name with file上传目录不发送文件夹名称和文件
【发布时间】:2018-02-26 18:29:03
【问题描述】:

我尝试了目录上传https://stackoverflow.com/a/8218074/2004910 的新功能,但我没有收到服务器请求的确切文件夹结构。

HTML

<form action="http://localhost:3000/" method="post" enctype="multipart/form-data">
<input id="files" class="file" type="file" name="file[]"  webkitdirectory directory>
<input type="submit" />

请求负载(网络面板)

ExpressJS:

const express = require('express')
const app = express()
var busboy = require('connect-busboy');
var fs = require('fs');
//...
app.use(busboy()); 

app.post('/', function (req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename) {
        console.log("Uploading: " + filename); 
        fstream = fs.createWriteStream(__dirname + '/files/' + filename);
        file.pipe(fstream);
        fstream.on('close', function () {
            res.redirect('back');
        });
    });
})
app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

请建议我如何实现这一目标。

【问题讨论】:

标签: javascript html node.js express


【解决方案1】:

来自https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory

用户做出选择后,文件中的每个文件对象都有自己的 File.webkitRelativePath 属性设置为内部的相对路径 文件所在的选定目录。

我不认为它很难在 POST 请求中传递,我认为你必须在客户端工作。

$('#files').on('change',function(e){
    var files = e.target.files;
    for (let i=0; i<files.length; i++) {
        var path = files[i].webkitRelativePath;
        $('#form').append('<input type="hidden" name="filepath[]" value="'+path+'"/>');
    }
});

此脚本将附加隐藏输入以通过 POST 发送文件路径。然后您的脚本可以使用它。请注意,如果我向您发送了一个文件名相同但位于两个不同文件夹中的文件,您可能不会将正确的文件放在正确的文件夹中。

【讨论】:

  • 这就是问题..如何在服务器上传递该信息?为此,客户端需要什么样的安排。
  • 截至目前,没有对我的 javascript/html 代码进行任何更改,我得到了所有文件的列表。我需要在服务器上没有收到但被传递到请求有效负载中的文件夹结构.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多