angular 找不到上传的图片 [英] angular does not find an uploaded image

查看:31
本文介绍了angular 找不到上传的图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景很简单.使用表单上传图片,如果上传成功,刷新相册.我使用 angular6 和 ng-carousel.所有系统都在我的 Windows 10 笔记本电脑中本地设置.

表单被上传,文本数据保存在数据库中,图像保存在节点 8.11.1 中的文件中.我将图像保存在 src/assets/images 中.我可以看到更改并且上传时没有错误.

但是,上传后,我尝试使用新图片的 URL 将其添加为轮播中的最后一张图片,但我得到的只是 404 错误.URL 类似于 http://localhost:4200/assets/images/unsplash.jpg URL 有效,图像在那里,所有其他轮播图像使用相同的 URL.但是,新图像有 404 错误.我必须重新编译角度应用程序才能看到图像.不只是刷新页面,而是重新编译整个应用程序.

我不知道如何解决这个问题.我尝试在前端使用 File 对象或 HTML5 FileReader API,而不依赖于在图像上传后创建 URL.但是它们没有 URL,并且 ng-carousel 需要一个像 /assets/images/img.jpg 这样的 URL 才能工作.为了使用某种 URL,我还尝试从 node 中获取临时 URL 并将其返回给前端,但由于它是一个 temp 文件夹 URL,浏览器不会让我使用它.我也尝试使用 createObjectURL 但并非所有浏览器都支持.我还尝试在保存图像后执行 GET 并从数据库中获取所有图像名称,再次循环它们并再次提供轮播模板.没有.还是404错误.我必须重新编译应用程序.

发生了什么?这是一个角度为 6 的问题吗?安全限制?请帮我解决这个问题,我不知道如何处理了.

代码概要.

表格

<form *ngIf="pointPartsActive" [formGroup]="imageUpload" (ngSubmit)="imageUploadSubmitted($event.target)" ><input type="file" (change)='imageChange($event)' #imageInput id="imageInput" name = 'imageInput' accept=".png, .jpg, .jpeg, .gif" formControlName="imageInput><input type="text" formControlName="imageName" name='imageName' placeholder="name" ><button type="submit" >Submit</button></表单>

html carousel 模板,添加自定义 html 也可以当场删除图像.

<ngb-carousel #carousel *ngIf="images" (slide)="onSlide($event)"><ng-template ngbSlide *ngFor="let im of images; let i = index" id="{{im.id}}"><img src='../assets/images/{{im.name}}' >

</ng-模板></ngb-carousel>

表单提交

 imageUploadSubmitted(form){让 formData = new FormData(form);让 eb =null;this.http.post('http://localhost:3000/cms/upload',formData,{reportProgress:true,observe:'events'}).subscribe(事件=>{if(event.type === HttpEventType.Response){eb = event.body;如果(成功){this.imageUpload.reset();this.addpic(eb.data);}}});}

成功提交表单后,更新提供轮播的数组.它是一个简单的 json 对象数组,如 [{'id':1,'name':'James'},{'id':2,'name':'Nolan'}] 和提要通过 ngFor 的轮播.

 addpic(data){让幻灯片 = 空;this.images.push({'photoId':Number(data.id)'id': this.images.length,'名称':data.name});//获取最后一张幻灯片的ID并转到那里:setTimeout(() => {幻灯片 = this.images[this.images.length-1].id;this.carousel.select(slide);});this.images = this.images.slice();//尝试刷新"数组本身}

stackblitz 中的代码逻辑

谢谢

解决方案

这可能是您的解决方案:

对于实时应用程序,您可能希望将图像保存在文件服务器上(例如 Amazon AWS 上的 AWS S3),并将指向该文件的链接存储在数据库中.

对于您的本地主机项目,您可以使用 http-server 作为此文件服务器或者您可以在您的节点应用程序中使用 express 框架.

npm install http-server -ghttp-server C:/link/to/a/folder/you/have/saved/the/images/in

然后您必须将链接保存在 db(数据库)或文本文件中.为此,我建议您设置本地 MongoDB 数据库.您可能需要一些时间才能进入,但这是很好的学习经验.您可以使用 https://mongoosejs.com/ 与您的节点应用程序进行通信.

然后,当您上传新图像时,将其从前端 Angular 应用程序发送到后端节点/express 应用程序,将文件保存在文件夹中并将链接保存在数据库中.使用 https 服务器,您将能够立即访问图像(可能会有一些延迟).通过存储在数据库中的链接,您可以在刷新应用程序时使用 http get 请求将数据库中的数据发送到前端.

我希望这能帮助您实现目标 :)

The scenario is simple. Use a form to upload an image and if it is successfully uploaded, refresh a photogallery. I use angular6 and ng-carousel. All the system is locally set in my windows 10 laptop.

The form gets uploaded, the text data are saved on the database and the image is saved in a file in node 8.11.1. I save the image in the src/assets/images. I can see the changes and I get no errors while uploading.

But, after the upload, I try to use the URL of the new image to add it as the last image in the carousel and all I get is a 404 error. The URL is like http://localhost:4200/assets/images/unsplash.jpg The URL is valid, the image is there and all the other carousel images use the same URL. But, the new image has a 404 error. I have to recompile the angular app to see the image. Not just refresh the page, recompile the whole app.

I dont know how to fix this. I tried using a File object or the HTML5 FileReader API on the front end and not depend on creating a URL after image upload. But they dont have a URL and the ng-carousel needs a URL like /assets/images/img.jpg to work. In order to use some kind of URL, I also tried to get the temporary URL from node and return it back to the front-end, but since it is a temp folder URL, browser wont let me use it. I also tried to use createObjectURL but is not supported in all browsers. I also tried to perform a GET after the image is saved and get all the images names from the database, to loop them again and feed the carousel template once again. Nothing. Still a 404 error. I have to recompile the app.

What is happening? Is this a angular 6 issue? Security restriction? Please help me fix this, I dont know how to deal with it anymore.

Outline of code.

the form

<form *ngIf="pointPartsActive" [formGroup]="imageUpload" (ngSubmit)="imageUploadSubmitted($event.target)" >
  <input type="file"  (change)='imageChange($event)' #imageInput id="imageInput" name = 'imageInput'  accept=".png, .jpg, .jpeg, .gif" formControlName="imageInput" > 
  <input type="text" formControlName="imageName" name='imageName' placeholder="name" >
  <button type="submit" >Submit</button>  
</form>

html carousel template, add custom html to also delete an image on the spot.

<ngb-carousel #carousel *ngIf="images" (slide)="onSlide($event)"> 
  <ng-template ngbSlide *ngFor="let im of images; let i = index"  id="{{im.id}}">
    <img src='../assets/images/{{im.name}}' >
    <div class='carousel-img-details'>
        <button type="button" (click)='deletepic(im.photoId)'>delete</button>   
    </div>
  </ng-template>
</ngb-carousel>

form submit

  imageUploadSubmitted(form){  
    let formData = new FormData(form);
    let eb =null;
    this.http.post('http://localhost:3000/cms/upload',formData,{reportProgress:true,observe:'events'}).subscribe(
      event=>{        
        if(event.type === HttpEventType.Response){     
          eb = event.body;              
          if(eb.success){                  
            this.imageUpload.reset();                                                 
            this.addpic(eb.data);            
          }
        }        
    }); 
  }

after successful form submit, update the array that feeds the carousel. Its a simple array of json objects like [{'id':1,'name':'James'},{'id':2,'name':'Nolan'}] and feeds the carousel via ngFor.

  addpic(data){
    let slide = null;    
    this.images.push({
        'photoId':Number(data.id)
        'id': this.images.length,   
        'name': data.name    
    });     
     //get the id of the last slide and go there :          
     setTimeout(() => {
      slide = this.images[this.images.length-1].id;    
      this.carousel.select(slide); 
     });
     this.images = this.images.slice(); //try to "refresh" array itself
  }

The code logic in stackblitz

Thanks

解决方案

This might be a solution for you:

For a live application you probably would want to save your images on a fileserver (for. example AWS S3 on Amazon AWS), and store the link to this file in a database.

For your localhost project you can use http-server to function as this fileserver or you can use the express framework with ur node application.

npm install http-server -g
http-server C:/link/to/a/folder/you/have/saved/the/images/in

Then you must save the link to your file, either in a db (database) or inn a textfile. For this I would recomend that you setup a local MongoDB database. This might take some time for you to get into, but it is good learning experience. You can use https://mongoosejs.com/ to communicate with your node application.

Then when you upload a new image, you send it from your frontend Angular app, to your backend node/express application, save the file in the folder and save the link in the db. With the https-server you will be able to access the image right away (with maybe som delay). And with the links stored in the db you can send the data in the db to your front end with a http get request whenever you refresh your application.

I hope this will help you to reach your goal :)

这篇关于angular 找不到上传的图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆