Click here to Skip to main content
15,886,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how do i create a bindable view for the below mentioned code, am new into knockout js, and i couldn't find any example regarding uploading images into database using web api and knockout js

What I have tried:

public class Agent
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ImagePath { get; set; }
}

my post api controller

public async Task<HttpResponseMessage> Post(Agent newAgent)
{
if (newAgent != null)
{
string regEx = "data:(.+);base64,(.+)";
Match match = Regex.Match(newAgent.ImagePath, regEx);
if (match.Success)
{
string imageType = match.Groups[1].Value;
string base64image = match.Groups[2].Value;

if (imageType != null && base64image != null)
{
string imageRegEx ="image/(.+)";
match = Regex.Match(imageType, imageRegEx);
if (match.Success)
{
string fileExtension = match.Groups[1].Value;
byte[] image = Convert.FromBase64String(base64image);

string path = HttpContext.Current.Server.MapPath("~/images");
string fileName = newAgent.FirstName + newAgent.LastName;


string targetFile = fileName + "." + fileExtension;
int index = 0;
while (File.Exists(Path.Combine(path, targetFile)))
{
index++;
targetFile = fileName + index + "." + fileExtension;
}

File.WriteAllBytes(Path.Combine(path, targetFile), image);
newAgent.ImagePath = "images/"; + targetFile;

newAgent = Database.AddAgent(newAgent);

var response = Request.CreateResponse(HttpStatusCode.Created, newAgent);
string uri = Url.Link("GetAgent", new { id = newAgent.Id });
response.Headers.Location = new Uri(uri);

return response;
}
}
}
}
throw new HttpResponseException(Request.CreateErrorResponse(
HttpStatusCode.BadRequest, "Could not deserialize agent"));

}
Posted
Updated 11-Apr-16 3:54am

1 solution

Hi,

Here is a link I think will help you with this issue(Upload files in ASP.NET MVC with JavaScript and C#.[^]), it uses ajax to return the file to the server then from there you can take the file and insert into your DB. You have not said what type of technology you are using for you DB connection (ole, odbc, entity) so I can't give you any advice on how to insert this into your DB. You also have not said what type of DB you are using(MS SQL, MY SQL, Access DB, MongoDB etc.). I hope this will help!!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900