טייפסקריפט - העלאת קבצים באנגולר
אני מתחיל עם Angular, אני רוצה לדעת איך ליצור ב-Angular 5 חלק העלאת קבצים, אני מנסה למצוא כל מדריך או מסמך, אבל אני לא רואה שום דבר בשום מקום. יש לך רעיון לגבי זה? וניסיתי את ng4-files אבל זה לא עובד עם Angular 5
תשובה #1
הנה דוגמה עובדת להעלאת קובץ ל-API:
שלב 1: תבנית HTML (file-upload.component.html)
הגדר תגית קלט פשוטה מסוג file. הוסף פונקציה לאירוע (change) כדי להתמודד עם בחירת קבצים.
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>
שלב 2: טיפול בהעלאות ב-TypeScript (file-upload.component.ts)
הגדר משתנה ברירת מחדל עבור הקובץ הנבחר.
fileToUpload: File | null = null;
צור פונקציה שבה תשתמש באירוע (change) של תגית קובץ הקלט שלך:
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
אם אתה רוצה להתמודד עם בחירת קבצים מרובים, אז אתה יכול לעבור דרך מערך הקבצים הזה.
עכשיו צור פונקציית העלאת קבצים על ידי קריאה ל-service-העלאת הקבצים שלך:
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
שלב 3: שירות העלאת קבצים (file-upload.service.ts)
על ידי העלאת קובץ באמצעות שיטת POST, עליך להשתמש ב-FormData, כי כך תוכל להוסיף קובץ לבקשת HTTP.
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
אז, זה דוגמה פשוטה מאוד לעבודה, שאני משתמש בה כל יום בעבודתי.
תשובה #2
כך אני מממש העלאת קובץ ל-API של האינטרנט בפרויקט.
אני משתף למען מי שזה נוגע לו.
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
צעד אחר צעד
ASP.NET Web API
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
טופס HTML
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
class="material-icons">save</i></button>
</div>
</form>
קובץ TS לשימוש ב-API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
שירות TS
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}
תשובה #3
השיטה הקלה והמהירה ביותר היא להשתמש ב-ng2-file-upload.
התקן את ng2-file-upload דרך npm. npm i ng2-file-upload --save
תחילה ייבא את המודול במודול שלך.
import { FileUploadModule } from 'ng2-file-upload';
Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]
סימון:
<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>
בקומפוננטה שלך ts:
import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });
זו השימוש הפשוט ביותר של זה. כדי לדעת את כל הכוח של זה ראו הדגמה
תשובה #4
- HTML
<div class="form-group">
<label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
</div>
<button type="button" (click)="RequestUpload()">Ok</button>
- קובץ ts
public formData = new FormData();
ReqJson: any = {};
uploadFiles( file ) {
console.log( 'file', file )
for ( let i = 0; i < file.length; i++ ) {
this.formData.append( "file", file[i], file[i]['name'] );
}
}
RequestUpload() {
this.ReqJson["patientId"] = "12"
this.ReqJson["requesterName"] = "test1"
this.ReqJson["requestDate"] = "1/1/2019"
this.ReqJson["location"] = "INDIA"
this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
this.http.post( '/Request', this.formData )
.subscribe(( ) => {
});
}
- Backend Spring (קובץ Java)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class Request {
private static String UPLOADED_FOLDER = "c://temp//";
@PostMapping("/Request")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
System.out.println("Json is" + Info);
if (file.isEmpty()) {
return "No file attached";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "Succuss";
}
}
אנחנו צריכים ליצור תיקייה בשם "temp" בכונן C, ואז הקוד הזה ידפיס את ה-Json בקונסולה וישמור את הקובץ שהועלה בתיקייה שנוצרה
תשובה #5
ראשית, עליך להגדיר את HttpClient בפרויקט Angular שלך.
פתח את הקובץ src/app/app.module.ts, ייבא את HttpClientModule והוסף אותו למערך ה-imports של המודול באופן הבא:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
לאחר מכן, צור רכיב:
ng generate component home
לאחר מכן, צור שירות העלאה:
ng generate service upload
לאחר מכן, פתח את הקובץ src/app/upload.service.ts באופן הבא:
import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UploadService {
SERVER_URL: string = "https://file.io/";
constructor(private httpClient: HttpClient) { }
public upload(formData) {
return this.httpClient.post<any>(this.SERVER_URL, formData, {
reportProgress: true,
observe: 'events'
});
}
}
לאחר מכן, פתח את הקובץ src/app/home/home.component.ts, והתחל על ידי הוספת הייבואות הבאים:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { UploadService } from '../upload.service';
לאחר מכן, הגדר את המשתנים fileUpload ו-files והזרק את UploadService בצורה הבאה:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
@ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files = [];
constructor(private uploadService: UploadService) { }
לאחר מכן, הגדירו את הפונקציה uploadFile():
uploadFile(file) {
const formData = new FormData();
formData.append('file', file.data);
file.inProgress = true;
this.uploadService.upload(formData).pipe(
map(event => {
switch (event.type) {
case HttpEventType.UploadProgress:
file.progress = Math.round(event.loaded * 100 / event.total);
break;
case HttpEventType.Response:
return event;
}
}),
catchError((error: HttpErrorResponse) => {
file.inProgress = false;
return of(`${file.data.name} upload failed.`);
})).subscribe((event: any) => {
if (typeof (event) === 'object') {
console.log(event.body);
}
});
}
לאחר מכן, הגדירו את הפונקציה uploadFiles() שניתן להשתמש בה כדי להעלות מספר קבצי תמונה:
private uploadFiles() {
this.fileUpload.nativeElement.value = '';
this.files.forEach(file => {
this.uploadFile(file);
});
}
לאחר מכן, הגדירו את הפונקציה onClick():
onClick() {
const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {
for (let index = 0; index < fileUpload.files.length; index++)
{
const file = fileUpload.files[index];
this.files.push({ data: file, inProgress: false, progress: 0});
}
this.uploadFiles();
};
fileUpload.click();
}
לאחר מכן, אנו צריכים ליצור את תבנית ה-HTML של ממשק העלאת התמונות שלנו. פתח את הקובץ src/app/home/home.component.html והוסף את התוכן הבא:
<div [ngStyle]="{'text-align':center; 'margin-top': 100px;}">
<button mat-button color="primary" (click)="fileUpload.click()">choose file</button>
<button mat-button color="warn" (click)="onClick()">Upload</button>
<input [hidden]="true" type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" />
</div>
בדוק את המדריך הזה ואת הפוסט הזה
