How to show uploaded images to the sever side once

2019-08-26 01:59发布

I am using MEAN stack to write and app to upload an image, to have a preview of it, and at the same time to upload this image to server(server in Express) and savinig it in MongoDB database. On the other hand side, I need this get this image back from Mongo and Server to display in on the browser once again. Here is my wiring: Client-side: Using Farid Daniel custsom directive the HTML uploading button is

<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>

to preview here:

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

and get uploaded to sever with this AngularJS codes:

    $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");
          });         

    }
  };

For the server-side I have written this:

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);
}
 );});

So far so good!, and this is what I get in the server side from one file

[ { 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' } ]

BUT, when I get this back on the client side to show to the user its image part fails. here is snipet of get codes in angularJS side.

      $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");
  });

With following error:

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

I couldn't find a similar question here, but I know it's commont action, and solution should be easy.

1条回答
甜甜的少女心
2楼-- · 2019-08-26 02:21

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

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

So you are wrongly using it to read files from server

edit

So what you need to do to display the image is to expose the candidate on scope that drives the view and then in view where you want to display the image

html

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

where candidate.name is name of the image file

查看更多
登录 后发表回答