簡體   English   中英

如何使用MEAN堆棧在瀏覽器中再次將上傳的圖像顯示到服務器端?

[英]How to show uploaded images to the sever side once again in browser using MEAN stack?

我正在使用MEAN堆棧編寫和應用程序以上傳圖像,預覽圖像,同時將此圖像上傳到服務器(Express中的服務器)並在MongoDB數據庫中進行保存。 另一方面,我需要將此圖像從Mongo和Server中取回,以再次顯示在瀏覽器中。 這是我的連線:客戶端:使用Farid Daniel custsom指令 ,HTML上傳按鈕為

<span class="btn btn-default btn-file">
    <input type="file" ngf-select ngf-change="uploadFile($files)" accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">Upload Image</input>
</span>

在這里預覽:

<img id="preview" src="http://lorempixel.com/150/150/fashion/" width="150px" height="150px" class="img-circle center"></img>

並使用以下AngularJS代碼上傳到服務器:

    $scope.uploadFile = function(files) {
    if(files.length > 0){
        var preview = document.getElementById("preview");
        preview.file = files[0];
      var reader = new FileReader();
      reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(preview);
      console.log(files[0]);
      reader.readAsDataURL(files[0]);
      // uploading image to server
      var filename = files[0].name;
      var type = files[0].type;
      var query = {
                  filename: filename,
                  type: type
                  };
          Upload.upload(
            {
              url: '/image/' + $rootScope.candidateList[parseInt(candiateIndex)]._id,
              method: 'PUT',
              // data: data // Any data needed to be submitted along with the files
              file: files
            }).progress(function(evt){
              // console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
          }).success(function(data, status, headers, config){
                 // console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
            console.log("Image succesfully uploaded to server");                     
          }).error(function(error){
            console.log("Error uploading image to server");
          });         

    }
  };

對於服務器端,我編寫了以下代碼:

app.put('/image/:id', multipartyMiddleware, function(req, res){
var id = req.params.id;
console.log('Server: I get a PUT request to update an image for candide');
var file = req.files.file;
console.log(file);
db.candidateList.findAndModify({
  query: {_id: mongojs.ObjectId(id)},
  update: {$set: {file: req.files.file}},
  new: true},
   function (err, doc) {
                res.json(doc);
}
 );});

到目前為止一切順利!,這就是我從一個文件進入服務器端的內容

[ { fieldName: 'file[0]',
originalFilename: '12095188_1085272848151633_8297555958524563020_o.png',
path: '/tmp/kHFe3Cm6w831_1lWQ6OEXlOE.png',
headers: 
 { 'content-disposition': 'form-data; name="file[0]"; filename="12095188_1085272848151633_8297555958524563020_o.png"',
   'content-type': 'image/png' },
size: 530699,
name: '12095188_1085272848151633_8297555958524563020_o.png',
type: 'image/png' } ]

但是,當我在客戶端將其重新顯示給用戶看時,其圖像部分將失敗。 這是在angularJS端獲取代碼的片段。

      $http.get('/condidateslist').success(function(data){
      $rootScope.candidateList = data;
          $rootScope.candide = $rootScope.candidateList[parseInt(candiateIndex)];
      console.log($rootScope.candide);
      var preview = document.getElementById("preview");
      preview.file = $rootScope.candide.file;
      var reader = new FileReader();
      reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(preview);
      reader.readAsDataURL($rootScope.candide.file); 
  }).error(function(error){
    console.log("Cant find contact information");
  });

有以下錯誤:

**TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.**

我在這里找不到類似的問題,但我知道這是常見的行動,解決方案應該很簡單。

來自https://developer.mozilla.org/en/docs/Web/API/FileReader

FileReader對象使Web應用程序可以使用File或Blob對象指定要讀取的文件或數據,以異步方式讀取存儲在用戶計算機上的文件(或原始數據緩沖區)的內容。

所以您錯誤地使用它從服務器讀取文件

編輯

因此,要顯示圖像,您需要在驅動視圖的范圍內顯示candidate ,然后在要顯示圖像的視圖中顯示candidate

html

<image ng-src="path/to/file/directory/{{candidate.name}}" />

其中candidate.name名稱是圖像文件的名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM