Azoulay Jason
Azoulay Jason

Reputation: 2999

GET Error 404 after file upload Angular 2+

I'm using multer to make an upload file system, everything works fine, the file is uploaded to the right folder which is src/assets/img/profile, but when I upload the file and refresh the page, the image doesn't display and I get a 404 error the file is not found in the browser console unless I run ng serve . What am I doing wrong ?

back end

function makeid() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './client/src/assets/img/profile');
  },
  filename: function (req, file, cb) {
    User.findOne({_id:req.decoded.userId},(err,user)=>{
        if(err){
            res.json({success:false,message:err});
        }
        else{
            if(!user){
                res.json({success:false,message:"User not found"});
            }
            else{
                cb(null, "profile" + user.username +makeid());
            }
        }

    });

  }
});
router.post('/edit-photo', upload,function (req,res){
        console.log(req.file);
      if (!req.file) {
        res.json({success:false,message:"No file was provided"});
      }
      else{
        User.findOne({_id:req.decoded.userId},(err,user)=>{
            if(err){
                res.json({success:false,message:'Something went wrong: '+err});
            }
            else{
                if (!user) {
                    res.json({success:false,message:'User not found'});
                }
                else{

                    user.img=req.file.filename;
                    user.save({ validateBeforeSave: false },(err)=>{
                        if(err){
                            res.json({success:false,message:'Something went wrong: '+err});
                        }
                        else{
                            res.json({success:true,file:req.file});
                        }
                    });
                }
            }
        });
      }
    });

For the front I send a XMLHttpRequest auth.service.ts

makeFileRequest(url: string,params: string[],files: File[]): Observable<any>{
    return Observable.create(observer => {
      let formData: FormData = new FormData();
      let xhr: XMLHttpRequest = new XMLHttpRequest();

      for(let i =0; i<files.length;i++){
        formData.append('file',files[i],files[i].name);
      }

      xhr.onreadystatechange = ()=>{
        if(xhr.readyState === 4){
          if(xhr.status===200){
            observer.next(JSON.parse(xhr.response));
            observer.complete();
          }
          else{
            observer.error(xhr.response);
          }
        }
      };

      xhr.upload.onprogress = (event)=>{
        this.progress = Math.round(event.loaded / event.total *100);

        this.progressObserver.next(this.progress);
      }
      xhr.open('POST',url,true);
      xhr.setRequestHeader('authorization',this.authToken);
      xhr.send(formData);
    });
  }

edit-profile.component.ts

upload(){
    this.authService.makeFileRequest('http://localhost:8080/authentication/edit-photo',[],this.filestoUpload).subscribe((data)=>{
      this.profilePic=data;
      window.location.reload();
    });
  }

  onFileChange(fileInput: any){
    this.filestoUpload=fileInput.srcElement.files;
  }

edit-profile.component.html

    <img  class="img-thumbnail img-responsive" [src]="profilePic" width="300px" height="300px">
  <label class="btn btn-default" for="file">Edit Photo</label>
  <input style="display: none;" id="file" type="file" name="file" (change)="onFileChange($event)">
<button (click)="upload()" class="btn btn-primary">Send</button>

Upvotes: 1

Views: 1305

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657741

<img class="img-thumbnail img-responsive" (src)="profilePic" width="300px" height="300px">

should be

<img class="img-thumbnail img-responsive" [src]="profilePic" width="300px" height="300px">

[] instead of ()

If you set profilePic

this.profilePic = this.profilePic + Date.now();

then the browser should reload the image. Ensure that you only upate profilePic after uploading the image is completed.

Upvotes: 1

Related Questions