2014-08-28 2 views
2

현재 내 응용 프로그램에 파일 업로드 시스템을 만들고 있습니다. 내 백엔드는 Sails.js (10.4)이며, 이는 별도의 프런트 엔드 (각도) 용 API로 사용됩니다.Sails.js는 skipper (유효 파일, 이미지 크기 조정 등)로 MongoDB에 파일을 업로드하기 전에 물건을 확인합니다.

나는 내 MongoDB 인스턴스에 업로드 할 파일을 저장하고 돛의 파일 업로드 모듈 Skipper 빌드를 사용하도록 선택했습니다. mongo에 파일을 업로드하려면 어댑터 skipper-gridfs (https://github.com/willhuang85/skipper-gridfs)를 사용하고 있습니다.

이제 파일 자체를 업로드하는 데 문제가 없습니다. 내 클라이언트에서 dropzone.js를 사용하여 업로드 된 파일을/api/v1/files/upload로 보냅니다. 파일이 업로드됩니다.

내가 내 FileController에 다음 코드를 사용하고이를 달성하기

이제
module.exports = { 
    upload: function(req, res) { 
     req.file('uploadfile').upload({ 
      // ...any other options here... 
      adapter: require('skipper-gridfs'), 
      uri: 'mongodb://localhost:27017/db_name.files' 
     }, function(err, files) { 
      if (err) { 
       return res.serverError(err); 
      } 
      console.log('', files); 
      return res.json({ 
       message: files.length + ' file(s) uploaded successfully!', 
       files: files 
      }); 
     }); 
    } 
}; 

문제 : 나는 그들이 업로드하기 전에 파일로 물건을하고 싶어. 특히 두 가지 :

  1. 파일이 허용되는지 확인하십시오. 콘텐츠 형식 헤더가 허용 할 파일 형식과 일치합니까? (jpeg, png, pdf 등 - 기본 파일들).
  2. 파일이 이미지 인 경우 이미지 파일 (또는 비슷한 이미지)을 사용하여 미리 정의 된 크기로 크기를 조정하십시오.
  3. 또한 파일을 업로드 한 사용자에 대한 참조 및 파일이 포함 된 모델 (즉, 기사/설명)에 대한 참조와 같이 데이터베이스에 저장되는 파일 별 정보를 추가하십시오.

시작하는 방법이나 이런 종류의 기능을 구현하는 방법에 대한 단서가 없습니다. 그래서 어떤 도움을 주시면 감사하겠습니다!

답변

1

.upload() 함수에 대한 콜백을 지정할 수 있습니다. 예 :

req.file('media').upload(function (error, files) { 
    var file; 

    // Make sure upload succeeded. 
    if (error) { 
    return res.serverError('upload_failed', error); 
    } 

    // files is an array of files with the properties you want, like files[0].size 
} 

당신은 .upload()의 콜백 내에서, 거기에서 업로드 할 파일 어댑터를 호출 할 수 있습니다.

+0

이렇게 올바르게 이해한다면, 먼저 업로드 된 파일을 .tmp/uploads 디렉토리에 저장하는 기본 .upload 함수를 사용해야하며 첫 번째 업로드 함수의 콜백에서 사용자 정의를 실행해야합니다. 물건 (파일 타입 등을 검사하는 것)을하고, skipper-gridfs를 사용하여 Mongo에게 보냅니 까? 첫 번째 콜백 파일의 .upload를 계속 호출 할 수 있습니까? – Darkstra

+0

나는 그렇다고 생각한다. 어디에서나 validate() 콜백이 보이지 않습니다. –

+0

어쩌면 내가 바보 같은 짓을하고있는 것 같지만 콜백에서 다음을 시도 할 때 files [0] .upload ({ '어댑터 : require ('skipper-gridfs '), uri :'mongodb : // localhost : 27017/evolution_api_v1.files '}, 함수 (오류, 파일) {...}); 콘솔에 '메소드 업로드가 없습니다'라는 메시지가 표시됩니다. 내가 기대했던 것. 또한 파일을 두 번 올리는 것이 필요하다고 생각합니다. 그것이 어떻게 든 업로드되기 전에 파일을 차단하는 것이 더 좋을 것 같습니다 .. 그것이 가능하다면 :). – Darkstra

7

좋아, 잠시 동안 만만치 않게 해보니 나는 그럭저럭 일할 수있는 방법을 찾을 수있었습니다.

그것은 아마 더 좋을 수 있지만, 그것이 내가 지금을 위해 수행 할 작업을 수행합니다

upload: function(req, res) { 
    var upload = req.file('file')._files[0].stream, 
     headers = upload.headers, 
     byteCount = upload.byteCount, 
     validated = true, 
     errorMessages = [], 
     fileParams = {}, 
     settings = { 
      allowedTypes: ['image/jpeg', 'image/png'], 
      maxBytes: 100 * 1024 * 1024 
     }; 

    // Check file type 
    if (_.indexOf(settings.allowedTypes, headers['content-type']) === -1) { 
     validated = false; 
     errorMessages.push('Wrong filetype (' + headers['content-type'] + ').'); 
    } 
    // Check file size 
    if (byteCount > settings.maxBytes) { 
     validated = false; 
     errorMessages.push('Filesize exceeded: ' + byteCount + '/' + settings.maxBytes + '.'); 
    } 

    // Upload the file. 
    if (validated) { 
     sails.log.verbose(__filename + ':' + __line + ' [File validated: starting upload.]'); 

     // First upload the file 
     req.file('file').upload({}, function(err, files) { 
      if (err) { 
       return res.serverError(err); 
      } 

      fileParams = { 
       fileName: files[0].fd.split('/').pop().split('.').shift(), 
       extension: files[0].fd.split('.').pop(), 
       originalName: upload.filename, 
       contentType: files[0].type, 
       fileSize: files[0].size, 
       uploadedBy: req.userID 
      }; 

      // Create a File model. 
      File.create(fileParams, function(err, newFile) { 
       if (err) { 
        return res.serverError(err); 
       } 
       return res.json(200, { 
        message: files.length + ' file(s) uploaded successfully!', 
        file: newFile 
       }); 
      }); 
     }); 
    } else { 
     sails.log.verbose(__filename + ':' + __line + ' [File not uploaded: ', errorMessages.join(' - ') + ']'); 

     return res.json(400, { 
      message: 'File not uploaded: ' + errorMessages.join(' - ') 
     }); 
    } 

}, 
대신 내가 로컬 파일 스토리지를 사용하기로 선택한 선장-gridfs를 사용

하지만 아이디어는 유지됩니다 같은. 다시 말하지만 아직 완벽하지는 않지만 파일 유형 및 크기와 같은 간단한 요소를 검증하는 쉬운 방법입니다. 누군가가 더 나은 해결책을 가지고 있다면, 그것을 게시하십시오 :)!