文件上传后获取错误404 Angular 2 +

时间:2017-08-30 00:09:15

标签: javascript angular file-upload

我正在使用multer制作上传文件系统,一切正常,文件上传到正确的文件夹,即src / assets / img / profile,但是当我上传文件并刷新页面时,图像没有显示,我收到404错误,在浏览器控制台中找不到该文件,除非我运行服务。我究竟做错了什么 ?

后端

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

前面我发送了一个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);
    });
  }

编辑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;
  }

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

1 个答案:

答案 0 :(得分:1)

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

应该是

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

[]代替()

如果设置profilePic

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

然后浏览器应该重新加载图像。 确保仅在上传图像后{}} 更新