簡體   English   中英

將圖像文件從 Angular 上傳到 Django REST ZDB974238714CA8DE634A7CE1D083A14F

[英]Upload image file from Angular to Django REST API

I want to select an image and POST that to the Django REST API that I have built but I am getting an error in doing so

""product_image": ["提交的數據不是文件。 檢查表單上的編碼類型。"]"

我可以創建和更新字符串和整數,但是當我嘗試添加圖像字段時出現此錯誤。 我可以通過 Postman 發布圖像,所以我不認為我的 API 有問題。

任何人都可以在這里幫助我,因為我環顧四周,但似乎找不到任何東西。

添加產品.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ApiService } from 'src/app/api.service';
import { Product } from 'src/app/models/Product';
import { Location } from '@angular/common';
import { Shop } from '../../../models/Shop';

@Component({
  selector: 'app-add-product',
  templateUrl: './add-product.component.html',
  styleUrls: ['./add-product.component.css']
})
export class AddProductComponent implements OnInit {

  product!: Product;
  selectedFile!: File;

  

  colours = [
    'Red',
    'Blue',
    'Orange',
    'Yellow',
    'White',
    'Black',
    'Navy',
    'Brown',
    'Purple',
    'Pink'
  ]
  categories = [
    'Food & Beverages',
    'Clothing & Accessories',
    'Home & Garden',
    'Health & Beauty',
    'Sports & Leisure',
    'Electronic & Computing'
  ]
  stock = [
    'In Stock',
    'Out Of Stock',
  ]

  productForm = new FormGroup({
    name: new FormControl(''),
    price: new FormControl(0.00),
    product_image: new FormControl(''),
    product_description: new FormControl(''),
    quantity: new FormControl(0),
    colour: new FormControl(''),
    stock: new FormControl(''),
    shipping_fee: new FormControl(0.00),
    weight: new FormControl(0.00),
    shop: new FormControl(''),
    category: new FormControl(''),
  });


  constructor(
    private route: ActivatedRoute,
    private apiService: ApiService,
    private location: Location,
    private router: Router,
    private postService: ApiService
  ) { }

  ngOnInit(): void {
  }

  goBack(): void {
    this.location.back();
  }

  onFileSelected(event: any) {
    this.selectedFile = <File>event.target.files[0]
    console.log(event)
  }

  addProduct(): void {
    console.log(this.productForm.value)
    this.apiService.addProduct(
      this.productForm.value
    ).subscribe(() => this.goBack(),
      result => console.log(result),
    );
  }
}


添加-product.component.html

<form [formGroup]="productForm">

    <label>Product Name</label><br>
    <input type="text" formControlName="name"><br>

    <label>Price</label><br>
    <input type="text" formControlName="price"/><br>

    <input type="file" formControlName="product_image" (change)="onFileSelected($event)"><br>


    <label>Description</label><br>
    <textarea type="text" formControlName="product_description"></textarea><br>

    <label>Quantity of Products</label><br>
    <input type="text" formControlName="quantity"/><br>

    <label>Colour of Product</label><br>
    <select formControlName="colour">
        <option value="" disabled>Choose a Colour</option>
        <option *ngFor="let colour of colours" [ngValue]="colour">
          {{ colour }}
        </option>
    </select><br>

    <label>Stock Availability</label><br>
    <select formControlName="stock">
        <option value="" disabled>Stock Availability</option>
        <option *ngFor="let stock of stock" [ngValue]="stock">
          {{ stock }}
        </option>
    </select><br>

    <label>Shipping Fee Price</label><br>
    <input type="text" formControlName="shipping_fee"/><br>

    <label>Weight (kg)</label><br>
    <input type="text" formControlName="weight"/><br>

    <label>Shop</label><br>
    <input type="text" formControlName="shop"/><br>

    <label>Category</label><br>
    <select formControlName="category">
        <option value="" disabled>Choose a Category</option>
        <option *ngFor="let category of categories" [ngValue]="category">
          {{ category }}
        </option>
    </select><br>
</form>


<button type="submit" (click)="addProduct()">Add</button>
<button (click)="goBack()">go back</button>

api.service.ts

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Product } from './models/Product';
import { CookieService } from 'ngx-cookie-service';
import { Category } from './models/Category';
import { Shop } from './models/Shop';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {


  baseUrl = 'http://127.0.0.1:8000/';
  baseProductUrl = `${this.baseUrl}app/products/`
  baseCategoryUrl = `${this.baseUrl}app/categories/`
  baseShopUrl = `${this.baseUrl}app/shops/`
  headers = new HttpHeaders({
    'Content-Type': 'application/json',
  });

  

  constructor(
    private httpClient: HttpClient,
    private cookieService: CookieService,
  ) { }

  /* Product CRUD */

  /* POST: add a product to the server */
  
  addProduct(product: Product) { 
    const productUrl = `${this.baseProductUrl}` 
    return this.httpClient.post<Product>(productUrl, product, {headers: this.getAuthHeaders()}) 
  }

  // DELETE: delete the product from the server 
  deleteProduct(product_code: number): Observable<Product> {

    const productUrl = `${this.baseProductUrl}${product_code}/`
    return this.httpClient.delete<Product>(productUrl, {headers: this.getAuthHeaders()})

  }

  // PUT: update the product on the server 
  updateProduct(product_code: number, product: Product): Observable<Product> {

    const productUrl = `${this.baseProductUrl}${product_code}/`
    return this.httpClient.put<Product>(productUrl, product, {headers: this.getAuthHeaders()})

  }

  // GET: get all products from the server 
  getProducts() {

    return this.httpClient.get<Product[]>(this.baseProductUrl, {headers: this.getAuthHeaders()});
    
  }

  // GET: get one product from the server 
  getProduct(product_code: number): Observable<Product> {
    const productUrl = `${this.baseProductUrl}${product_code}/`
    return this.httpClient.get<Product>(productUrl, {headers: this.getAuthHeaders()});
    
  }

  // GET: get all categories from the server 
  getCategories() {

    return this.httpClient.get<Category[]>(this.baseCategoryUrl, {headers: this.getAuthHeaders()});
    
  }

  // GET: get one category from the server 
  getCategory(id: number): Observable<Category> {
    const url = `${this.baseCategoryUrl}${id}/`;

    return this.httpClient.get<Category>(url, {headers: this.getAuthHeaders()});
    
  }

  // GET: get all shops from the server 
  getShops() {

    return this.httpClient.get<Shop[]>(this.baseShopUrl, {headers: this.getAuthHeaders()});
    
  }

  // GET: get one shop from the server 
  getShop(business_reg: string): Observable<Shop> {
    const url = `${this.baseShopUrl}${business_reg}/`;

    return this.httpClient.get<Shop>(url, {headers: this.getAuthHeaders()});
    
  }

  
  

  

  loginUser(authData: any) {
    const body = JSON.stringify(authData);
    return this.httpClient.post(`${this.baseUrl}auth/`, body, {headers: this.headers});
  }

  registerUser(authData: any) {
    const body = JSON.stringify(authData);
    return this.httpClient.post(`${this.baseUrl}user/users/`, body, {headers: this.headers});
  }

  getAuthHeaders() {
    const token = this.cookieService.get('ur-token')
    return new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: `Token ${token}`
    });
  }

}

內容類型必須是multipart/form-data而不是application-json這樣您就可以將文件發送到 API

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM