简体   繁体   中英

path mapping not working properly with Angular and NestJs

I'm facing a scenario right now that is quite odd to me, when I upload a product from Angular to NestJs with the image. First time when I upload it uploads the product and image to server, but it does not attach the image path with the product. when I upload the second product , then it uploads the product with image, and this time the path mapping works, it uploads the 2nd product and the 2nd image to server, but it attaches the path of the first image with second product, and when I uploads the third product , it attaches the path of the 2nd image with 3rd product, and this goes on. Now I don't understand this, some solution for this please.

在此处输入图像描述

In the above screen shot you can see the example of my problem. First time from input field, from Angular side, it selects the theoram1(a).png, but the image didn't get attached with the product. But the image is uploaded to server along side other properties,

Second time it selects the theoram2.png, but it attaches the thoram1(a).png with second product. And this goes on like this.

Angular side code. From here I'm selecting and uploading image and product to server. adbooks.component.ts

@Component({
  selector: 'app-adbooks',
  templateUrl: './adbooks.component.html',
  styleUrls: ['./adbooks.component.css'],
})
export class AdbooksComponent implements OnInit {      AddbookForm = new FormGroup({
    bid: new FormControl(''),
    name: new FormControl(''),
    author: new FormControl(''),
    price: new FormControl(''),
    genres_name: new FormControl(''),
    coverimage: new FormControl(''),
  });
  constructor(
    private readonly apiService: ApiService,
    private readonly router: Router,
    private readonly http: HttpClient
  ) {}

  ngOnInit() {}

  async addall() {
    this.addfile();
    this.addbooks();
    this.AddbookForm.reset();
  }
  async addfile() {
    let formData = new FormData();
    formData.set(
      'file',
      this.AddbookForm.value.coverimage,
      this.AddbookForm.value.coverimage.name
    );
    this.http
      .post('http://localhost:3000/images/upload', formData, {
        responseType: 'text',
      })
      .subscribe((res) => {});
  }
  async addbooks() {
    (await this.apiService.addbooks(this.AddbookForm.value)).subscribe(
      (res) => {
        console.log(res);
      }
    );
  }

  async uploadimage(event: any) {
    this.AddbookForm.value.coverimage = event.target.files[0];
    console.log('file', this.AddbookForm.value.coverimage);
  }
}

NestJs side code. Here I'm uploading the image and attaching path with product(Book). images.controller.ts

@Controller('images')
export class ImagesController {
  static imageUrl: string;
  constructor(private readonly bookservice: BooksService) {}

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './assets/',
        filename: (req, file, cb) => {
          const filename: string = Array(10)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          return cb(null, `${filename}${extname(file.originalname)}`);
        },
      }),
    }),
  )
  async uploadFile(@UploadedFile() file: Express.Multer.File, @Request() req) {
    console.log(file);
    return this.imageUrl(file);
  }

  private imageUrl(file: Express.Multer.File) {
    ImagesController.imageUrl = `./assets/${file.originalname}`;
    return ImagesController.imageUrl;
  }
}

NestJS side code. books.service.ts.Here I'm attaching the image path with book's coverimage property

async addbooks(book: Book): Promise<bookdocument> {
    book.coverimage = ImagesController.imageUrl;
    return await this.book_model.create(book);
  }

The issue was with this logic.Due to this logic Not just I was unable to upload files with correct path,also I was not able to preview when the image gets selected.This function does not convert the selected image, into a viewable format.Because we need to convert our selected image into src='' readable/acceptable formate.

 async uploadimage(event: any) {
    this.AddbookForm.value.coverimage = event.target.files[0];
    console.log('file', this.AddbookForm.value.coverimage);
  }

Use this Function instead.This is the right logic to read and preview files

 imagedata?: string;
async uploadimage(event: any) {
    const file = event.target.files[0];
    this.AddbookForm.patchValue({ coverimage: file });
    const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];
    if (file && allowedMimeTypes.includes(file.type)) {
      const reader = new FileReader();
      reader.onload = () => {
        this.imagedata = reader.result as string;
      };
      reader.readAsDataURL(file);
      console.log(file);
    }
  }

html code

 <div class="text-center">
                    <input
                      type="file"
                      id="form3Example4cdg"
                      class="form-control form-control-lg"
                      (change)="uploadimage($event)"
                    />
                    <br />
                    <div *ngIf="imagedata">
                      <img
                        [src]="imagedata"
                        alt=""
                        width="400px"
                        height="400px"
                      />
                    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM