如何在 Angular2 中 post 图片?
How to post image in Angular2?
实际上是 Angular2 的新手。在 post 方法中,我不知道如何在 angular2 中上传图片。
其他字段也有(产品名称、类型、类别 ..等)以及我想要 post 图像。
下面我提到了我的 Html、conponent.ts 和 service.ts。
所以请告诉我该怎么做?
HTML
<div class="form-group image">
<input type="file" (change)="onfileSelected($event)" class="form-control" multiple="">
<span style="padding-left:22%">
<a href="#">
<i class="fa fa-pencil fa-lg" aria-hidden="true"></i>
</a> |
<a href="#">
<i class="fa fa-trash-o fa-lg" aria-hidden="true"></i>
</a>
</span>
</div>
Component.ts
onfileSelected(event) {
console.log(event);
this.selectedFile = <File>event.target.files[0];
}
createNewProduct(productForm: NgForm) {
this.productService.save_user(productForm.value)
.subscribe(response => {
const toast_parameter = this.notificationService.getToast('success', 'New Product', 'Inserted Successfully');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
},
error => {
const toast_parameter = this.notificationService.getToast('error', 'New Product', 'Error Occurred!!');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
});
}
Service.ts
save_user(product_data: any): Observable<any[]> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
return this.http.post('http://localhost:8000/product/', product_data, httpOptions)
.map(response => response)
.catch(error => Observable.throw(error.statusText));
};
model.py
class Product(models.Model):
image = models.ImageField(upload_to='myphoto/%Y/%m/%d/', null=True, max_length=255)
pro_name = models.CharField(max_length=25)
description = models.CharField(max_length=150)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
sales = models.CharField(max_length=25)
cost = models.CharField(max_length=25)
taxable = models.BooleanField(default=False, blank=True)
tax_details= models.CharField(max_length=250)
type_units = models.ForeignKey(Units, on_delete=models.CASCADE)
hsn = models.CharField(max_length=10)
serializer.py
class ProductSerializer(serializers.HyperlinkedModelSerializer):
image = serializers.ImageField(required=False, max_length=None, allow_empty_file=True, use_url=True)
class Meta:
model = Product
fields = ('id','image','pro_name','description','category','sales','cost','taxable','tax_details','type_units','hsn')
您好,您可以将使用 http 调用插入的服务更改为 XMLHttpRequest
file:File;
onfileSelected(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
if(files) {
this.file: File = files[0];
}
}
public save_user(filedata: File) {
let url = 'your url'
if (typeof filedata != 'undefined') {
return new Promise((resolve, reject) => {
let formData: any = new FormData();
let xhr = new XMLHttpRequest();
formData.append('image', filedata, filedata.name);
xhr.open('POST', url, true);
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
resolve(JSON.parse(xhr.responseText));
}
}
});
}
}
更新:
this.service.saveUser(this.file)
.then(data=>{
console.lo(' image File uploaded')
})
在您的后端,您可以从 request.FILES
image = request.FILES['image']
要发送 image/file,您需要以 FormData
的形式发送数据,因此将您的全部数据添加到 formData 中并将其发送回您的服务器
<input type="file" (change)="onfileSelected($event.target.files)" class="form-control" multiple="">
onfileSelected(event) {
console.log(event);
this.form.image = <File>event.target.files[0];
}
createNewProduct() {
this.productService.save_user(this.setFormData(this.form.value))
.subscribe(response => {
const toast_parameter = this.notificationService.getToast('success', 'New Product', 'Inserted Successfully');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
},
error => {
const toast_parameter = this.notificationService.getToast('error', 'New Product', 'Error Occurred!!');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
});
}
setFormData(param) {
let formData = new FormData();
for (let i = 0; i < Object.keys(param).length; i++) {
let key = Object.keys(param)[i];
let data = param[key];
formData.append(key, data);
}
return formData;
}
实际上是 Angular2 的新手。在 post 方法中,我不知道如何在 angular2 中上传图片。 其他字段也有(产品名称、类型、类别 ..等)以及我想要 post 图像。 下面我提到了我的 Html、conponent.ts 和 service.ts。 所以请告诉我该怎么做?
HTML
<div class="form-group image">
<input type="file" (change)="onfileSelected($event)" class="form-control" multiple="">
<span style="padding-left:22%">
<a href="#">
<i class="fa fa-pencil fa-lg" aria-hidden="true"></i>
</a> |
<a href="#">
<i class="fa fa-trash-o fa-lg" aria-hidden="true"></i>
</a>
</span>
</div>
Component.ts
onfileSelected(event) {
console.log(event);
this.selectedFile = <File>event.target.files[0];
}
createNewProduct(productForm: NgForm) {
this.productService.save_user(productForm.value)
.subscribe(response => {
const toast_parameter = this.notificationService.getToast('success', 'New Product', 'Inserted Successfully');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
},
error => {
const toast_parameter = this.notificationService.getToast('error', 'New Product', 'Error Occurred!!');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
});
}
Service.ts
save_user(product_data: any): Observable<any[]> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
return this.http.post('http://localhost:8000/product/', product_data, httpOptions)
.map(response => response)
.catch(error => Observable.throw(error.statusText));
};
model.py
class Product(models.Model):
image = models.ImageField(upload_to='myphoto/%Y/%m/%d/', null=True, max_length=255)
pro_name = models.CharField(max_length=25)
description = models.CharField(max_length=150)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
sales = models.CharField(max_length=25)
cost = models.CharField(max_length=25)
taxable = models.BooleanField(default=False, blank=True)
tax_details= models.CharField(max_length=250)
type_units = models.ForeignKey(Units, on_delete=models.CASCADE)
hsn = models.CharField(max_length=10)
serializer.py
class ProductSerializer(serializers.HyperlinkedModelSerializer):
image = serializers.ImageField(required=False, max_length=None, allow_empty_file=True, use_url=True)
class Meta:
model = Product
fields = ('id','image','pro_name','description','category','sales','cost','taxable','tax_details','type_units','hsn')
您好,您可以将使用 http 调用插入的服务更改为 XMLHttpRequest
file:File;
onfileSelected(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
if(files) {
this.file: File = files[0];
}
}
public save_user(filedata: File) {
let url = 'your url'
if (typeof filedata != 'undefined') {
return new Promise((resolve, reject) => {
let formData: any = new FormData();
let xhr = new XMLHttpRequest();
formData.append('image', filedata, filedata.name);
xhr.open('POST', url, true);
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
resolve(JSON.parse(xhr.responseText));
}
}
});
}
}
更新:
this.service.saveUser(this.file)
.then(data=>{
console.lo(' image File uploaded')
})
在您的后端,您可以从 request.FILES
image = request.FILES['image']
要发送 image/file,您需要以 FormData
的形式发送数据,因此将您的全部数据添加到 formData 中并将其发送回您的服务器
<input type="file" (change)="onfileSelected($event.target.files)" class="form-control" multiple="">
onfileSelected(event) {
console.log(event);
this.form.image = <File>event.target.files[0];
}
createNewProduct() {
this.productService.save_user(this.setFormData(this.form.value))
.subscribe(response => {
const toast_parameter = this.notificationService.getToast('success', 'New Product', 'Inserted Successfully');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
},
error => {
const toast_parameter = this.notificationService.getToast('error', 'New Product', 'Error Occurred!!');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
});
}
setFormData(param) {
let formData = new FormData();
for (let i = 0; i < Object.keys(param).length; i++) {
let key = Object.keys(param)[i];
let data = param[key];
formData.append(key, data);
}
return formData;
}