angular上傳圖片到.netcore後端

克里斯同學發表於2019-03-18

html程式碼

input設定display:none,通過點選button觸發file input

<input id="upload" type="file" name="files" accept="image/*">
<button ion-button icon-only (click)="triggerFileUpload($event)">
    <ion-icon name="camera-outline"></ion-icon>
</button>

複製程式碼

預覽

<img [src]="url" class="image-preview" />
複製程式碼

angular ts程式碼

triggerFileUpload方法

triggerFileUpload(event: any) {
    let element: HTMLElement = document.getElementById('upload') as HTMLElement;
    element.click();
    element.onchange = (e: any) => {
        if (e.target && e.target.files.length) {
            let reader = new FileReader();
            reader.onload = (onloadEvent: any) => {
              this.url = onloadEvent.target.result;
            }

            reader.readAsDataURL( e.target['files'].item(0));
        }
        
        // this.imageUpload.nativeElement.value = '';
    }
}
複製程式碼

angular service

FileUpload(file: File): Promise<any> {
    return new Promise((resolve, reject) => {
        const formData: FormData = new FormData();
        formData.append('files', file, file.name)

        this.http.post(APIConstant.FileUpload,formData).subscribe(result => {
            resolve(result);
        });
    });
}
複製程式碼

dotnet core 程式碼

model

public class FileUploadModel
{
    public IFormFile files { get; set; }
}
複製程式碼

[FromForm] recieve params

[HttpPost]
public async Task<IActionResult> FileUpload([FromForm]FileUploadModel files)
{
    ...
    var stream = files.files.OpenReadStream();
    ...
}
複製程式碼

相關文章