[英]storing and retrieving images from database using asp.net web api and knockout js
我的實體
public class Agent
{
[Key]
[JsonProperty(PropertyName = "agentId")]
public int AgentId { get; set; }
[JsonProperty(PropertyName = "codeName")]
public string CodeName { get; set; }
[JsonProperty(PropertyName = "firstName")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "lastName")]
public string LastName { get; set; }
[JsonProperty(PropertyName = "imagePath")]
public string ImagePath { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
}
我的視圖模型
public class AgentVm
{
public int AgentId { get; set; }
public string CodeName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ImagePath { get; set; }
public string Description { get; set; }
}
我的Get Web API控制器
public IQueryable<AgentVm> GetAgents()
{
var agents = from b in db.Agents
select new AgentVm()
{
AgentId = b.AgentId,
FirstName = b.FirstName,
LastName = b.LastName,
CodeName = b.CodeName,
ImagePath = b.ImagePath
};
return agents;
}
我的帖子Web API控制器
public async Task<HttpResponseMessage> PostAgent(Agent agent)
{
if (agent != null)
{
// Extract the image from the image string
string regEx = "data:(.+);base64,(.+)";
Match match = Regex.Match(agent.ImagePath, regEx);
if (match.Success)
{
// Get the content-type of the file and the content
string imageType = match.Groups[1].Value;
string base64image = match.Groups[2].Value;
if (imageType != null && base64image != null)
{
// Verify the content-type is an image
string imageRegEx = "image/(.+)";
match = Regex.Match(imageType, imageRegEx);
if (match.Success)
{
// Get the file extension from the content-type
string fileExtension = match.Groups[1].Value;
// Get the byte-array of the file from the base64 string
byte[] image = Convert.FromBase64String(base64image);
string path = HttpContext.Current.Server.MapPath("~/images");
string fileName = agent.FirstName + agent.LastName;
// Generate a unique name for the file (add an index to it if it already exists)
string targetFile = fileName + "." + fileExtension;
int index = 0;
while (File.Exists(Path.Combine(path, targetFile)))
{
index++;
targetFile = fileName + index + "." + fileExtension;
}
// Write the image to the target file, and update the agent with the new image path
File.WriteAllBytes(Path.Combine(path, targetFile), image);
agent.ImagePath = "images/" + targetFile;
db.Agents.Add(agent);
await db.SaveChangesAsync();
// Create the Location http header
var response = Request.CreateResponse(HttpStatusCode.Created, agent);
string uri = Url.Link("GetAgent", new { id = agent.AgentId});
response.Headers.Location = new Uri(uri);
return response;
}
}
}
}
throw new HttpResponseException(Request.CreateErrorResponse(
HttpStatusCode.BadRequest, "Could not deserialize agent"));
}
這是我的js
var ViewModel = function() {
var self = this;
self.agents = ko.observableArray();
self.error = ko.observable();
self.agent = ko.observableArray();
self.newAgent = {
FirstName: ko.observable(),
LastName: ko.observable(),
CodeName: ko.observable(),
Description: ko.observable(),
ImagePath: ko.observable()
}
var agentsUrl = "/api/agents/";
function ajaxHelper(uri, method, data) {
self.error(""); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: "json",
contentType: "application/json",
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllAgents() {
ajaxHelper(agentsUrl, "GET").done(function (data) {
self.agents(data);
});
}
self.addAgent = function (formElement) {
var agent = {
AgentId: self.newAgent.Agent().AgentId,
FirstName: self.newAgent.FirstName(),
LastName: self.newAgent.LastName(),
CodeName: self.newAgent.CodeName(),
Description: self.newAgent.Description(),
ImagePath: self.newAgent.ImagePath()
};
ajaxHelper(agentsUrl, 'POST', agent).done(function (item) {
self.agents.push(item);
});
}
getAllAgents();
};
ko.applyBindings(new ViewModel());
這是我的形象元素
<img data-bind="attr:{ src: ImagePath }"/>
但是圖像沒有顯示,我想不起來要添加一個上傳文件,請有人幫助,我不需要angular,只是一個簡單的mvvm(如敲除js),但它相對較新。
查看使用Chrome控制台生成的<img>
元素,或使用firefox的Firebug(特別是src屬性)。 然后將URL復制到新選項卡中,並檢查其是否顯示。 我認為您的問題是該元素已正確呈現,但是您的項目無法呈現直接圖像,因為MVC會嘗試使用路由邏輯來查找您請求的控制器/操作,並返回HTTP404。 請檢查此響應以獲取解決方案
您可以創建一個簡單的表單來上傳文件,或者如果要使用ajax,則可以使用jquery $ .post。 這是一個示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.