[英]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 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": ["The submitted data was not a file. ""product_image": ["提交的数据不是文件。 Check the encoding type on the form."]"检查表单上的编码类型。"]"
I can create and update strings and integers but when I try add the image field I get this error.我可以创建和更新字符串和整数,但是当我尝试添加图像字段时出现此错误。 I can POST images through Postman so I don't think its my API that's at fault.我可以通过 Postman 发布图像,所以我不认为我的 API 有问题。
Can anyone help me out here as I have looked around but can't seem to find anything.任何人都可以在这里帮助我,因为我环顾四周,但似乎找不到任何东西。
add-product.component.ts添加产品.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),
);
}
}
add-product.component.html添加-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 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}`
});
}
}
The content-type must be multipart/form-data
instead of application-json
that way you can send files to an API内容类型必须是multipart/form-data
而不是application-json
这样您就可以将文件发送到 API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.