I have module to upload file in Angular 7 Reactive Forms ( I need reactive form because I need to upload files and some other information together)
I follow this article: https://medium.com/@amcdnl/file-uploads-with-angular-reactive-forms-960fd0b34cb5
the code as follow: https://pastebin.com/qsbPiJEX
onFileChange(event) {
const reader = new FileReader();
if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.formGroup.patchValue({
file: reader.result
});
// need to run CD since file load runs outside of zone
this.cd.markForCheck();
};
}
}
as far I know, I will receive the file as text inside the json data.
But I have no idea how to receive this as a file or convert the json data to file. The file could be images, pdf or other docs (excel, docs, or other formats)
I am using Dotnet Core 2.2 and Angular 7
Any idea how to receive the file ?
I'm having a form in which i want to post image through formData, i got fileobject in my FormControl just by putting this attribute writeFile="true"
. This can write the FileList object in your FormControl as value. To Achieve this you need to install the package of '@rxweb/reactive-form-validators' and register the 'RxReactiveFormsModule' module. That's it.
here is my html code :
<form [formGroup]="userFormGroup">
<label>Profile Photo</label>
<input type="file" [writeFile]="true" formControlName="profilePhoto" multiple />
<button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
</form>
Please refer this example : Stackblitz
we are sending the file in request-body of the request so we can get the file in request using the below code. So we can access file in our request using below code
using System.IO;
var filelocation = Path.GetTempFileName();
foreach (var FileData in Request.Form.Files)
{
if (FileData.Length > 0)
{
using (var inputStream = new FileStream(filelocation , FileMode.Create))
{
// read file to stream
await FileData.CopyToAsync(inputStream);
// stream to byte array
byte[] array = new byte[inputStream.Length];
inputStream.Seek(0, SeekOrigin.Begin);
inputStream.Read(array, 0, array.Length);
// get file name
string fName = formFile.FileName;
}
}
}