Having some issues trying to pass FormData from an Angular 12 app to a .Net Core API. Every attempt to send the data gets denied in preflight and never actually calls the backend endpoint (confirmed with Console.WriteLine there).
Followed the same patterns in many videos and websites and even created a side projected where it was able to work but for some reason in the main app it never sends. Only difference is that our main app uses PrimeNG as a framework so that is the main driver of collecting the files from the users. I've read their documentation but still not having success with it. Hopefully someone out there can help.
Attachment-Form Component
File Upload <span class="example-text">(Max File Size: 10MB)</span>
<p-fileUpload
#form
name="fileUpload[]"
multiple="multiple"
accept="{{ acceptedFiles }}"
maxFileSize="10000000"
customUpload="true"
(uploadHandler)="uploadFiles($event)"
>
<ng-template pTemplate="content">
<div
*ngIf="form.files.length === 0 && uploadedFiles.length === 0"
class="drag-drop"
>
<i class="pi pi-clone me-2"></i>DRAG & DROP FILES OR CLICK CHOOSE | THEN
PRESS UPLOAD
</div>
<div *ngIf="uploadedFiles.length !== 0">
<div class="p-fileupload-row" *ngFor="let file of uploadedFiles; let i">
<div class="p-fileupload-filename">
{{ file.name }} - {{ file.size }} bytes
</div>
<div>
<button
type="button"
icon="pi pi-trash"
pbutton
(click)="showFile(file)"
class="p-element p-button p-component p-button-icon-only p-button-danger"
>
<span class="p-button-icon pi pi-trash" aria-hidden="true"></span
><span aria-hidden="true" class="p-button-label"> </span>
</button>
</div>
</div>
</div>
</ng-template>
</p-fileUpload>
</div>
<div>
File Upload <span class="example-text">(Max File Size: 10MB)</span>
<p-fileUpload
#form
name="fileUpload[]"
multiple="multiple"
accept="{{ acceptedFiles }}"
maxFileSize="10000000"
customUpload="true"
(uploadHandler)="uploadFiles($event)"
>
<ng-template pTemplate="content">
<div
*ngIf="form.files.length === 0 && uploadedFiles.length === 0"
class="drag-drop"
>
<i class="pi pi-clone me-2"></i>DRAG & DROP FILES OR CLICK CHOOSE | THEN
PRESS UPLOAD
</div>
<div *ngIf="uploadedFiles.length !== 0">
<div class="p-fileupload-row" *ngFor="let file of uploadedFiles; let i">
<div class="p-fileupload-filename">
{{ file.name }} - {{ file.size }} bytes
</div>
<div>
<button
type="button"
icon="pi pi-trash"
pbutton
(click)="showFile(file)"
class="p-element p-button p-component p-button-icon-only p-button-danger"
>
<span class="p-button-icon pi pi-trash" aria-hidden="true"></span
><span aria-hidden="true" class="p-button-label"> </span>
</button>
</div>
</div>
</div>
</ng-template>
</p-fileUpload>
</div>
Form Component (for custom upload event)
uploadFiles(event) {
let files: any = <File>event.files;
// console.log(files);
const fileData = new FormData();
for (let i = 0; i < files.length; i++) {
fileData.append('file', files[i], files[i].name);
// Console Log for my sake
fileData.forEach((item) => console.log('fileData', item));
}
this.attachmentsService.uploadFiles(fileData).subscribe(
(res) => console.log(res),
(err) => console.log(err)
);
}
Attachment Service
uploadFiles(upload: any) {
//Confirmation they are still there
upload.forEach((item) => console.log('in api call', item));
return this.http.post(
'apiendpoint',
upload
);
}
//I've used these headers and additional content-type headers as well and nothing worked
headers = new HttpHeaders()
.set('content-type', 'application/json')
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', '*');
Any ideas are apricated. Thanks,
2/7 Update for API Info
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AttachmentService", Version = "v1" });
});
services.AddCors(c => {
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.AddDbContext<AttachmentContext>(options =>
options.UseNpgsql(Configuration["PGConnection"]));
services.AddScoped<IAttachmentData, AttachmentData>();
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AttachmentService v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowOrigin");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Controller
// [HttpOptions] <- Currently commented just as trial but doesn't work while on
[HttpPost, Route("files")]
public ActionResult<string> PostFiles(IFormCollection formData)
{
Console.WriteLine("post fired");
// rest of logic
}