I have an application in Angular 4 for file upload and a server in .NET Core 2.
This is my api method:
[HttpPost]
[Route("PostFileUploadIFile")]
public async Task<IActionResult> PostFileUpload(APIDocumentsSettings aPIDocumentsSettings)
{
try
{
var fileUpload = aPIDocumentsSettings.FileForUpload;
if (fileUpload.Length < 0 || fileUpload == null)
{
return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Incorrect Base64 format" });
}
string fileDir = Path.Combine(hostingEnvironment.WebRootPath, aPIDocumentsSettings.DocumentType, aPIDocumentsSettings.Version);
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
string file = Path.Combine(fileDir, DateTime.Now.Ticks + ".pdf");
if (!string.IsNullOrEmpty(fileUpload.FileName))
{
byte[] filebytes = Convert.FromBase64String(fileUpload.FileName);
FileStream fs = new FileStream(file,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None);
fs.Write(filebytes, 0, filebytes.Length);
fs.Close();
}
using (var fs = new FileStream(Path.Combine(file), FileMode.Create))
{
await fileUpload.CopyToAsync(fs);
}
if (String.IsNullOrEmpty(file))
{
return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "File Upload Failed, Path not found!" });
}
return Ok(file.Substring(file.LastIndexOf(aPIDocumentsSettings.DocumentType)));
}
catch (Exception ex)
{
return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Exception Occurs" + ex.Message });
}
}
This is my APIDocumentsSettings
Model:
public class APIDocumentsSettings
{
public IFormFile FileForUpload { get; set; }
public string Version { get; set; }
public string DocumentType { get; set; }
}
This is contained in the startup of the web api project:
public class Startup
{
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MastersDbContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
//services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services.AddAuthentication()
.AddOAuthValidation();
services.AddAuthentication(options =>
{
options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
});
services.AddAuthorization(options =>
{
options.AddPolicy("RequiredApplicationManagerRole", policy => policy.RequireRole("ApplicationManager"));
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Masters API",
Description = "Masters API give access to all Masters table Web APIs",
TermsOfService = "None"
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Masters API");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder =>
builder.WithOrigins("*")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
);
app.UseMvc();
app.UseAuthentication();
app.UseStaticFiles();
}
}
This is my angular code:
@Injectable()
export class DocumentupdatingService
{
apiRoot:string="http://localhost:8080/api/v1/";
constructor(private _http:Http)
{ }
create(documentupdating:DocumentsUpdating)
{
return this._http.post(this.apiRoot+'DocumentsSettings',documentupdating)
}
destroy(documentupdating:DocumentsUpdating)
{
return this._http.delete(this.apiRoot+documentupdating.id).map(res=>res.json())
}
update(documentupdating:DocumentsUpdating)
{
return this._http.put(this.apiRoot+'DocumentsSettings/'+documentupdating.id,documentupdating)
}
getAllDocuments()
{
return this._http.get("http://192.168.91.39:8080/api/v1/DocumentsSettings").map(res=>res.json())
}
uploadFile(formdata:FormData)
{
console.log(formdata.get('FileForUpload'))
console.log(formdata.get('Version'))
console.log(formdata.get('DocumentType'))
let myHeader = new Headers();
myHeader.append('Content-Type','multipart/form-data');
let options=new RequestOptions({headers:myHeader});
return this._http.post(this.apiRoot+'DocumentsSettings/PostFileUploadIFile/',{'FileForUpload':formdata.get('FileForUpload'),'Version':formdata.get('Version').toString,'DocumentType':formdata.get('DocumentType')},options)
}
}
After Uploading file I get following error:
I have uploaded file through PostMan and its working.