【问题标题】:GET Error 404 after file upload Angular 2+文件上传 Angular 2+ 后 GET 错误 404
【发布时间】:2018-02-07 13:19:00
【问题描述】:

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

后端

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

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>

【问题讨论】:

  • 您只需要在&lt;img&gt; 标签中设置图片的url 并使用一些虚拟(唯一/以前未使用)查询参数,以使浏览器重新加载图片。

标签: javascript angular file-upload


【解决方案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();

然后浏览器应该重新加载图像。 确保您只更新profilePic上传图片完成后。

【讨论】:

  • 还是不行,也许我应该提供我的后端/后端代码以便你理解
  • 我认为我不需要你的后端代码。而是您用来上传的 Angular 代码。您需要确保仅在上传完成后更改this.profilePic
  • 好的,我明白了,我要上传的所有角度代码都在这里。我需要检查 observable 以查看上传何时完成对吗?
  • 好的,谢谢各位,我会试试的。如果我有问题,我可能会回来找你..
  • 您需要仔细检查浏览器尝试从中加载图像的 URL,以及图像实际存储的路径以及不匹配的内容。
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 2017-10-02
  • 2017-05-22
  • 2017-07-20
相关资源
最近更新 更多