Update database where ID is specified after File Upload is complete. asp.net web api
I want to update the FileName column in the database whenever i have successfully uploaded a file to the web api. I will specify the Id in my url when im posting the file through postman for example http//localhost/PhysioWebPortal/api/PerformedExercises/PostFile/1014 , where 1014 is the id Can anyone help me with the updating database part? I have attached a image of the database as well.
T
his is the code for the post:
// POST: api/PerformedExercises/Post
[HttpPost]
[ResponseType(typeof(PerformedExercis))]
//[Route("{Id}")]
[Route("PostFile/{id}")]
public HttpResponseMessage PostFile(int id , PerformedExercis performed)
{
//Check if Request contains any File or not
if (HttpContext.Current.Request.Files.Count == 0)
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var httpRequest = HttpContext.Current.Request;
var docfiles = new List();
foreach (string files in httpRequest.Files)
{
var postedFile = httpRequest.Files[files];
string filePath = HttpContext.Current.Server.MapPath("~/Uploaded/" + (DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss")) + postedFile.FileName);
Console.WriteLine(postedFile.FileName);
Console.WriteLine(filePath);
var provider = new MultipartFormDataStreamProvider(filePath);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
//Read the File data from Request.Form collections.
HttpPostedFile uploadedFile = HttpContext.Current.Request.Files[0];
//Convert the File data to Byte Array which will be store in database
byte[] bytes;
using (BinaryReader br = new BinaryReader(uploadedFile.InputStream))
{
bytes = br.ReadBytes(uploadedFile.ContentLength);
}
//Retrieve and update database
if (performed.FileName == null)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
else
{
//Insert the File to Database Table - performedExercises
PHYSIODBEntities f_Entities = new PHYSIODBEntities();
PerformedExercis file = new PerformedExercis
{
FileName = Path.GetFileName(uploadedFile.FileName)
};
f_Entities.SaveChanges();
f_Entities.PerformedExercises.Add(file);
return Request.CreateResponse(HttpStatusCode.OK, new { Name = file.FileName });
}
}
0 comments:
Post a Comment