2017-07-19 32 views
0

所以我們得到的前端有一個文件(圖像文件),像這樣:從瀏覽器到JFrog/Artifactory的服務器POST二進制數據,而無需使用表單數據

// HTML

<input type="file" ng-change="onFileChange"> 

// javascript

$scope.onFileChange = function (e) { 
     e.preventDefault(); 
     let file = e.target.files[0]; 
     // I presume this is just a binary file 
     // I want to HTTP Post this file to a server 
     // without using form-data 
    }; 

我想知道的是 - 有沒有辦法將這個文件發佈到服務器,而不包括該文件作爲form-data?問題是我發送HTTP POST請求的服務器,在收到請求時並不真正知道如何存儲表單數據。

我相信這是正確的做法,但我不確定。

fetch('www.example.net', { // Your POST endpoint 
    method: 'POST', 
    headers: { 
     "Content-Type": "image/jpeg" 
    }, 
    body: e.target.files[0] // the file 
    }) 
    .then(
    response => response.json() // if the response is a JSON object 
) 
+1

爲什麼你不確定你的方法是否是「正確的做法」?是的,您應該可以將'Blob'或'File'實例POST到服務器 – guest271314

+0

@AlexanderMills:但是,當服務器收到帶有image/jpeg類型的POST請求時必須知道該怎麼做。你使用什麼服務器? –

+0

我們需要HTTP POST/PUT到一個JFrog Artifactory服務器 - 我最終使用我們的服務器作爲Artifactory服務器的代理。我將添加一個答案,顯示我們是如何做到的。也許有人可以看我的答案,並顯示如何可以避免代理。 –

回答

0

我們的前端無法直接HTTP POST到JFrog/Artifactory服務器。所以我們最終使用Node.js服務器作爲代理,這不是很理想。

前端:

// in an AngularJS controller: 

    $scope.onAcqImageFileChange = function (e) { 

      e.preventDefault(); 
      let file = e.target.files[0]; 
      $scope.acqImageFile = file; 
     }; 

// in an AngularJS service 

    createNewAcqImage: function(options) { 

     let file = options.file; 

     return $http({ 
      method: 'POST', 
      url: '/proxy/image', 
      data: file, 
      headers: { 
      'Content-Type': 'image/jpeg' 
      } 
     }) 
     }, 

後端:

const express = require('express'); 
const router = express.Router(); 

router.post('/image', function (req, res, next) { 

    const filename = uuid.v4(); 

    const proxy = http.request({ 
    method: 'PUT', 
    hostname: 'engci-maven.nabisco.com', 
    path: `/artifactory/cdt-repo/folder/${filename}`, 
    headers: { 
     'Authorization': 'Basic ' + Buffer.from('cdt-deployer:foobar').toString('base64'), 
    } 
    }, function(resp){ 
    resp.pipe(res).once('error', next); 
    }); 

    req.pipe(proxy).once('error', next); 
}); 

module.exports = router; 

不是我們不得不使用一個PUT請求發送的圖像artifactory的,而不是帖子,是與Artifactory的(engci-maven.nabisco.com服務器是Artifactory服務器)。我記得,當我試圖直接從前端發佈到其他服務器時,我遇到了CORS問題,所以我們不得不使用我們的服務器作爲代理,這是我寧願避免的,但是現在好了。

相關問題