2017-01-02 3 views
0

노드 응용 프로그램을 쓰고 서버에서 파일을 업로드 할 대상을 찾고있었습니다. 하나의 정적 디렉토리가있을 때 업로드 할 파일을 얻을 수있었습니다. 하지만 로그인 한 사용자에 따라 사용자별로 디렉토리를 만들고 그 파일을 업로드해야합니다. 내가 보았지만 내가 시도한 모든 것이 오류로 끝납니다 : ENOENT : 해당 파일이나 디렉토리가 열려 있지 않습니다 ... 오류 . 내가 현재 할 시도하고 이것이다 -multer : 동적 대상 경로

let storage = multer.diskStorage({ 
    destination: function(req, file, cb) { 
    let dest = path.join(__dirname, './documents', 'somenameigetfromtheuser'); 
    let stat = null; 
    try { 
     stat = fs.statSync(dest); 
    } 
    catch (err) { 
     fs.mkdirSync(dest); 
    } 
    if (stat && !stat.isDirectory()) { 
     throw new Error('Directory cannot be created'); 
    } 
    cb(null, dest); 
    } 
}); 

let upload = multer({ 
    storage: storage, 
    dest: 'documents/' 
}); 

app.post('/testUpload', upload.single('testfile'), (req, res) => { 
    res.json({ 
    test: 'test' 
    }) 
}); 

대답 된 similar question있다하지만 난 요청 객체에서 디렉토리 이름을 원하기 때문에 나를 위해 그런 식으로 작동하지 않습니다.

내 multer 초기화에서 저장소 속성을 제거하면 파일이 임의의 이름으로 문서 디렉토리에 저장됩니다. 파일의 원래 이름을 원하고 req 객체에서 디렉토리의 이름을 가져 오는 디렉토리에 저장하려고합니다.
형제, 감사합니다 도와주세요! 내 프로젝트에서

+0

하는 편집 답변을 참조를 저를 위해 작동하는). –

답변

0

나는 다음과 같이 multer를 사용

1.Store 파일을 먼저 공통 디렉토리에서/tmp를 /처럼.

2. 원하는 경우 파일을 내 케이스의 CDN 및 귀하의 사용자 폴더로 복사/이동하십시오.

3. 필요한 경우/tmp에있는 원본 파일을 제거하십시오.

어쩌면 let upload = multer({ storage: storage, dest: 'documents/' }); 어쩌면 저장소에 dest를 지정했기 때문에 dest를 삭제해야합니다. 맞습니까?

+0

그리고 파일을 어떻게 옮깁니 까? 이 이름 바꾸기를 시도했지만, 전혀 작동하지 않습니다. – Zeokav

+0

글쎄요, node.js에서 다른 파일에 파일을 쓰는 것에 대한 또 다른 질문이 있습니다. http://stackoverflow.com/questions/11293857/fastest-way-to-copy-file-in-node-js – YLS

0

이 때문에 것과 https://github.com/expressjs/multer#diskstorage

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

를 참조

편집, 임시 디렉토리에 처음 쓰기 파일은 REQ에서 디렉토리 이름을 읽고 파일 이동 : (

fs = require('fs-extra'); //npm install fs.extra 
... 

var storage = multer.diskStorage({ 
    destination: function (req, file, cb) { 
     cb(null, '../tempDir/') 
    }, 
    filename: function (req, file, cb) { 
     cb(null, file.originalname) 
    } 
}); 

var upload = multer({ 
    storage: storage 
}).single('file'); 

upload(req, res, function (err) { 
    if (err) { 
     res.json({}); 
     return; 
    } 

    var dir = JSON.parse(req.body.data).directory; 
    var filename = req.file.filename; 

    fs.move('../tempDir/' + fileName, '../tempDir/' + dir + '/' + fileName, function (err) { 
     if (err) { 
      return console.error(err); 
     } 

     res.json({}); 
    }); 

});