上传图像并在上传后查看

时间:2018-10-11 04:08:06

标签: laravel angular5

我正在尝试在Angular 5.2和Laravel 5.5中上传个人资料图片。我可以成功将图像上传到本地存储中的单独文件夹中。然后,我想显示与Facebook中相同的上载图像。然后,我可以查看上传的图像,但是它没有上传到该文件夹​​。这是我当前的代码。它通过在append,event下划线显示错误。

/* This is the most basic of requirements -- see demo for a better set of CSS rules */
selector {font-family: 'Open Sans'}

可以使用laravel代码上传到文件夹的代码在这里。

<!doctype html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
  <style>
    html {
      font: 400 16px/1.5 'Open Sans';
    }
    
    body {
      font-size: 1.1rem
    }
  </style>
</head>

<body>

  <h1>Open Sans</h1>
  <p>Apparently we had reached a great height in the atmosphere, for the sky was a dead black, and the stars had ceased to twinkle. By the same illusion which lifts the horizon of the sea to the level of the spectator on a hillside, the sable cloud beneath
    was dished out, and the car seemed to float in the middle of an immense dark sphere, whose upper half was strewn with silver.</p>

</body>

</html>

服务文件

 uploadFile(event) {
if (event.target.files.length > 0) {
  const reader = new FileReader();
  reader.append('myfile', elem.files[0]);
  reader.readAsDataURL(event.target.files[0]);
  reader.onload = (event) => {
    this.url = event.target.result;
  };
  this.fileService.sendFile(reader).subscribe(
        (response) => {
          console.log(response);
        });}
 }

这是我在laravel中的文件控制器

uploadFile(event){    
const elem = event.target;  
if(elem.files.length > 0){     
  const formData = new FormData();  
  formData.append('myfile', elem.files[0]);  
  this.fileService.sendFile(formData).subscribe( 
    (response) => {
console.log(response);
    }); }
elem.value = ""; 
}

使用波纹管代码,打开图像后即可查看图像。

export class FileService {

constructor(private httpClient: HttpClient) { }

sendFile(formData: any) {
  const baseUrl = 'http://127.0.0.1:8000/api';
  const url = `${baseUrl}/file`;
  return this.httpClient.post(
  url,
  formData);
  }
 }

1 个答案:

答案 0 :(得分:1)

我可以将图像上传到本地存储中的文件夹,同时我可以使用以下代码查看它。但是它仍然显示结果错误。我需要知道正确的方法。

  

错误TS2339:类型“”上不存在属性“结果”   EventTarget”。

代码在这里。

uploadFile(event) {
if (event.target.files.length > 0) {
  const reader = new FileReader();
  const formData = new FormData();
  formData.append('myfile', event.target.files[0]);
  reader.readAsDataURL(event.target.files[0]);
  reader.onload = (event) => {
    this.url = event.target.result;
  };
  this.fileService.sendFile(formData).subscribe(
        (response) => {
          console.log(response);
        });
}
event.target.value = '';
}