When it comes to uploading files and FormData to a server, I found a method that works well:
On the client side, I am using Angular 2 with the following logic:
1. In the component
onLoadForeignLightCompanies(event: any) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('projectId', this.projectId);
formData.append('file', file);
this.companyService.uploadForeginLightCompany(formData).then(result => {});
this.isLoading = false;
window.location.reload();
}
}
2. In the service
uploadForeginLightCompany(formData: FormData): Promise<any> {
return this.http.post(this.baseUrl + 'foreignLightCompanyImport', formData).toPromise();
}
On the server side
public byte[] LoadUploadedFile(HttpPostedFile uploadedFile)
{
var buf = new byte[uploadedFile.InputStream.Length];
uploadedFile.InputStream.Read(buf, 0, (int)uploadedFile.InputStream.Length);
return buf;
}
[HttpPost, Route("foreignLightCompanyImport")]
public async void UploadForeignLigtCompanyCompanyFile()
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var file = LoadUploadedFile(HttpContext.Current.Request.Files[0]);
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
var projectId = provider.FormData.GetValues("projectId")[0];
((IForeginLightCompanyService) Service).UploadDataFromExcel(file, Convert.ToInt32(projectId));
}
A common practice on the server side is to use
HttpContext.Current.Server.MapPath("~/App_Data");
However, this saves the files on disk. Is there a way to upload a file without saving it to disk while still being able to retrieve other parameters like projectId
? Perhaps sending the file as binary string in JSON with other parameters from a model on the client side could be a solution. Does anyone have any insights or suggestions regarding this issue?