简体   繁体   English

使用asp.net Web API和敲除JS从数据库存储和检索图像

[英]storing and retrieving images from database using asp.net web api and knockout js

my entity 我的实体

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; }        
    }

my Viewmodel 我的视图模型

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; }
    }

my Get web api controller 我的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;
    }

my post web api controller 我的帖子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"));
}

and this is my js 这是我的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());

and this is my image element 这是我的形象元素

<img data-bind="attr:{ src: ImagePath }"/>

but the image is not displaying and i can't figure out to add an upload, please someone help , i don't need angular , just a simple mvvm such as knockout js but am relative new in it. 但是图像没有显示,我想不起来要添加一个上传文件,请有人帮助,我不需要angular,只是一个简单的mvvm(如敲除js),但它相对较新。

Look at the generated <img> element with Chrome console, or Firebug from firefox (specially the src property). 查看使用Chrome控制台生成的<img>元素,或使用firefox的Firebug(特别是src属性)。 Then copy the URL in a new tab and check if its displayed. 然后将URL复制到新选项卡中,并检查其是否显示。 I think your problem is that the element is rendered correctly, but your project cannot render direct images, as MVC will try to use the route logic to find the controller/action you are requesting, returning an HTTP 404. Check this response for a solution 我认为您的问题是该元素已正确呈现,但是您的项目无法呈现直接图像,因为MVC会尝试使用路由逻辑来查找您请求的控制器/操作,并返回HTTP404。 请检查此响应以获取解决方案

You can create a simple form to upload files, or perhaps you can use jquery $.post, if you want to use ajax. 您可以创建一个简单的表单来上传文件,或者如果要使用ajax,则可以使用jquery $ .post。 Here is a sample for that 这是一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 c# 中使用 asp.net 将图像存储在数据库中 - Storing images inside a database using asp.net in c# 在 asp.net 核心中的每个请求中将用户数据存储在 session 存储中还是从数据库中检索? - Storing user data in session store or retrieving from database in each request in asp.net core? 如何从 ASP.NET Web API 获取 Angular 中的图像? - How to get images in Angular from an ASP.NET Web API? 从数据库存储和检索图像 - Storing and retrieving images from Database 如何在 ASP.NET Core web 应用程序中使用 Entity Framework Core 从数据库中保存和检索图像? - How to save and retrieve images from database using Entity Framework Core in ASP.NET Core web application? 使用 ASP.NET Web API 在数据库中发布十进制值 - Post a decimal value in database using ASP.NET Web API ASP.NET SlideShowExtender 从 web 服务中检索图像,但执行时什么也不做 - ASP.NET SlideShowExtender retrieving images from web service, but doing nothing when executed 在ASP.NET Web窗体网站上存储和显示图像 - Storing And Displaying Images On ASP.NET Web Forms Website 从数据库在asp.net Web API中流式传输视频 - stream video in asp.net web api from database 从MySQL数据库检索具有固定尺寸的图像后,如何在ASP.NET中显示它们 - How to display images with fixed dimensions in ASP.NET after retrieving them from a MySQL database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM