Pipe a uploaded file to a remote server with node (ideally with same filename)

前端 未结 3 1410
时光说笑
时光说笑 2020-12-15 07:36

I want to upload a file in my app.js server , which should pipe that file to a crossdomain server like my upload.js server.

The full code can be found under the foll

3条回答
  •  感动是毒
    2020-12-15 08:23

    Updated

    I believe you're missing the protocol from the url. It should work, if you add the http protocol to the url:

    fs.createReadStream(file.path).pipe(request.post('http://localhost:4000/upload'))
    

    Make Upload work

    When you pipe the file contents to the POST function in upload.js, the multipart form data is lost. You need to create a new POST request and pass the original file contents.

    Do the following in app.js:

     form.on('file', function(name, file) {
    
        var formData = {
          file: {
            value:  fs.createReadStream(file.path),
            options: {
              filename: file.originalFilename
            }
          }
        };
    
        // Post the file to the upload server
        request.post({url: 'http://localhost:4000/upload', formData: formData});
    }
    

    This will also pass the original filename. For more information see: https://github.com/request/request#multipartform-data-multipart-form-uploads

提交回复
热议问题