<input (change)="onFileSelected()" ng2FileSelect [uploader]="uploader" type="file" id="file">
<ion-button class="input-group-text upload" (click)="uploader.uploadAll()" >Upload</ion-button>
后端
app.post('/api/upload', upload.single('pdf'), function (req, res) {
console.log('File is available!');
return res.send({
success: true
})
});
现在我有用户在资产中选择的图像路径
imagePathToUpload:string = './assets/emojis/'+this.selectedEmoji
topPosition:number = this.topPos
leftPosition:number = this.leftPos
我如何将所有这些数据一起发送到服务器,有一种方法 FormData 但我不明白如何使用它。
目标是将图像、Pdf、左侧和顶部位置发送到服务器。任何建议将不胜感激。
创建上传方法
FinalformData: FormData;
uploadFile(event) {
if (event.target.files && event.target.files.length > 0) {
const file = event.target.files[0];
this.FinalformData = new FormData();
this.FinalformData.append('file', file, file.name);
}
}
submit() {
// call your service and send it
this._sendfileService.sendFile(this.FinalformData)
.subscribe( res => {
if (res.success) {
console.log('file uploaded');
} else { console.log('faild uploading file'))}
})
}
现在一切都完成了,使用您的 http.post 方法调用您的角度服务,这里是和前
sendFile(file: FormData): Observable<any> {
return this.http.post<any>(this.nodejsUrl, file);
}
要在后端处理文件,请查看 multer
<input (change)="onFileSelected($event)" type="file" id="file">
<ion-button class="input-group-text upload" (click)="uploadData()">Upload</ion-button>
import { Component } from '@angular/core';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
selectedPdf: File; // To store the selected PDF file
selectedImage: File; // To store the selected image file
topPosition: number; // Assuming these are initialized elsewhere in your code
leftPosition: number; // Assuming these are initialized elsewhere in your code
constructor(private http: HttpClient) {}
// Method to handle file selection
onFileSelected(event: any) {
const file = event.target.files[0];
// Check if file is a PDF or an image
if (file.type === 'application/pdf') {
this.selectedPdf = file;
} else if (file.type.startsWith('image/')) {
this.selectedImage = file;
} else {
console.error('Unsupported file type');
}
}
// Method to upload data to the server
uploadData() {
if (!this.selectedPdf || !this.selectedImage) {
console.error('Please select both a PDF file and an image');
return;
}
// Prepare data
const formData = new FormData();
formData.append('pdf', this.selectedPdf);
formData.append('image', this.selectedImage);
formData.append('topPosition', this.topPosition.toString());
formData.append('leftPosition', this.leftPosition.toString());
// Send data to server
this.http.post('/api/upload', formData).subscribe(
(response) => {
console.log('Data successfully sent to server:', response);
},
(error) => {
console.error('Error sending data to server:', error);
}
);
}
}