来自 Multer 前端的自定义文件名

Custom file name from frontend in Multer

我正在使用 FormData 上传文件并使用 Multer 在服务器端接收它。一切都按预期工作,除了因为我在前端使用文件系统 API (https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry), the files I'm uploading come from sub-directories. Multer seems to only see the filename, even if I explicitly set an alias for the file as I append it to form data (https://developer.mozilla.org/en-US/docs/Web/API/FormData/append)。似乎 Multer 在我的请求处理程序的其余部分之前执行其逻辑,并且看不到我在主体上设置的参数。如何让 multer 查看完整路径?

这是我当前设置的简化版本:

Client(别名表示带路径的全名,file.name是文件系统API自动设置的基本名称):

function upload(file, alias) {
    let url = window.location.origin + '/upload';
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    xhr.open('POST', url, true);

    return new Promise(function (resolve, reject) {

        xhr.addEventListener('readystatechange', function(e) {
            if (xhr.readyState == 4 && xhr.status == 200) {
                resolve(file.name);
            }
            else if (xhr.readyState == 4 && xhr.status != 200) {
                reject(file.name);
            }
        })

        formData.append('file', file, alias || file.name); // this should in theory replace filename, but doesn't
        formData.append('alias', alias || file.name); // an extra field that I can't see in multer function at all
        xhr.send(formData);
    });
}

服务器:

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        // neither req nor file seems to contain any hint of the alias here
        cb(null, file.originalname);
    }
});
const upload = multer({storage: storage});
const bodyParser = require('body-parser');
app.use(bodyParser.json());

app.post('/upload', upload.single('file'), function (req, res, next) {
    // by this time the file seems to already be on disk with whatever name multer picked
    if (req.file) {
        res.status(200).end();
    } else {
        res.status(500).end();
    }
});

为了让它工作,在配置 multer 时使用 preservePath 选项。以下 起作用:

const upload = multer({storage: storage, preservePath: true});

但是,请务必注意,multer 不会 创建目录或子目录。这些必须事先创建。 (我也测试了这个。如果目录已创建且为空,则上传成功,但是,如果目录不存在,则上传失败)。

在他们的 readme 中,他们说: "Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you."

该注释的 follow-up 将是:"you are responsible for creating any sub-directories too".

上传文件的相对路径将在 originalname 属性 中访问。所以,后端看起来像这样:(正如你所拥有的,但有更新的评论)

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        // If you uploaded for example, the directory: myDir/myFile.txt,
        // file.originalname *would* be set to that (myDir/myFile.txt)
        // and myFile.txt would get saved to uploads/myDir
        // *provided that* uploads/myDir already exists.
        // (if it doesn't upload will fail)
        // /* if(  [ uploads/myDir doesn't exist ] ) { mkdir } */
        cb(null, file.originalname);
    }
});

有用提示: 在前端,我发现使用以下方法更容易测试目录/子目录上传:(在 Chrome 上测试最新 ok)

<form action="/uploads/multipleFiles" method="post" enctype="multipart/form-data">
      <input type="file" name="multiple" webkitdirectory accept="text/*" onchange="console.log(this.files)" />
      <input type="text" name="tester" value="uploadTester" />
      <input type="submit"/>
</form>

如果你想上传护照图片作为正面和背面,那么从前端传递参数,像这样 user:"username"type:"front “键入:“返回” 然后像这样在节点端使用它

const upload = multer({
    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'uploads/passport/');
        },
        filename: function (req, file, cb) {
            cb(null, req.body.user+"-"+req.body.type+".jpg");
        }
    })
});