【问题标题】:how to construct url for image saved in database如何为保存在数据库中的图像构造url
【发布时间】:2016-02-09 18:22:56
【问题描述】:

我遇到了问题。我的数据库已正确配置,图像已正确保存在数据库中,但不知道如何为保存在数据库中的图像构造 url,因为我必须将其提供给敲除视图模型进行绑定。

  public JsonResult GetPosts()
    {
        var ret = (from post in db.Posts.ToList()
                   orderby post.PostedDate descending
                   select new
                   {
                       Message = post.Message,
                       PostedBy = post.PostedBy,
                       PostedByName = post.ApplicationUser.UserName,
 // having problem at this line dont know how to construct url at this line as i have to supply url
 // (String type to the PostedByAvatar)
                       PostedByAvatar = db.Files.SingleOrDefault(s => s.ApplicationUserId == post.PostedBy),
                       PostedDate = post.PostedDate,
                       PostId = post.PostId,
                   }).AsEnumerable();
        return Json(ret, JsonRequestBehavior.AllowGet);
    }

这是淘汰功能--------

    function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.PostedByName = data.PostedByName || "";

self.PostedDate = getTimeAgo(data.PostedDate);
self.PostedByAvatar = data.PostedByAvatar || "";
self.error = ko.observable();
self.PostComments = ko.observableArray();

这是从数据库中获取现有帖子、评论等的视图模型-----

    function viewModel() {
    var self = this;
    self.posts = ko.observableArray();
    self.newMessage = ko.observable();
    self.error = ko.observable();
    self.loadPosts = function () {
        // to load existing posts
        $.ajax({
            url: postApiUrl1,
            datatype: "json",
            contentType: "application/json",
            cache: false,
            type: 'Get'
        })

在我的视图页面上,这是用于加载带有帖子的图像的容器框-----

    <ul id="msgHolder" data-bind="foreach: posts">
    <li class="postHolder">
    <img data-bind="attr: { src: PostedByAvatar }">
    <p><a data-bind="text: PostedByName"></a>: <span data-bind=" html: Message"></span></p>

现在,将图像保存在数据库中的模型类是这样的。它有ApplicationUserId作为指向ApplicationUserClass的外键---

   public class File
   {
    [Key]
    public int FileId { get; set; }
    [StringLength(255)]
    public string FileName { get; set; }
    [StringLength(100)]
    public string ContentType { get; set; }
    public byte[] Content { get; set; }
    public FileType FileType { get; set; }
    public int ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
   }

ApplicationUserClass 是这样的---

  public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
   {
    public ApplicationUser()
    {
        this.Posts = new HashSet<Post>();
        this.Files = new HashSet<File>();
    }
    public virtual ICollection<File> Files { get; set; }
    public virtual ICollection<Post> Posts { get; set; }

这是保存在数据库中的图像。现在,我想知道如何为保存在数据库中的图像构造 url,因为我必须以字符串形式将其提供给视图模型。或者有比这更好的方法。

这是我的 Post 类,它与 ApplicationUser 类有多对一的关系,外键是 PostedBy 指向 ApplicationUser 类----

   public class Post
   {
    public Post()
    {
        this.PostComments = new HashSet<PostComment>();
    }
    [Key]
    public int PostId { get; set; }
    public string Message { get; set; }
    public int? PostedBy { get; set; }
    public System.DateTime PostedDate { get; set; }
    public virtual ICollection<PostComment> PostComments { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

【问题讨论】:

    标签: c# asp.net-mvc sql-server-2008 knockout.js linq-to-entities


    【解决方案1】:

    虽然可以将 Base64 字符串作为 srcsrc 传递,但我认为最明智的方法是不从 Ajax 调用返回实际字节,而是创建一个请求来自服务器的图像字节。

    首先,添加将提供图像数据所需的操作:

    [HttpGet]
    public FileResult GetFileData(int fileId)
    {
        var file = db.Files.Single(x => x.FileId == fileId);
    
        return File(file.Content, file.ContentType);
    }
    

    现在,将您的 GetPosts 操作更改为在 PostedByAvatar 属性中返回 url:

    public JsonResult GetPosts()
    {
        var ret = (from post in db.Posts.ToList()
                   orderby post.PostedDate descending)
                   select new
                   {
                       Message = post.Message,
                       PostedBy = post.PostedBy,
                       PostedByName = post.ApplicationUser.UserName,
                       PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),
                       PostedDate = post.PostedDate,
                       PostId = post.PostId,
                   });
    
        return Json(ret, JsonRequestBehavior.AllowGet);
    }
    
    private string _GenerateAvatarUrlForUser(int? userId)
    {
        if (!user.HasValue)
            return null;
    
        var avatarImage = db.Files.SingleOrDefault(s => s.ApplicationUserId == userId);
    
        if (avatarImage != null)
            return Url.Action("GetFileData", new { fileId = avatarImage.FileId });
    
        return null;
    }
    

    【讨论】:

    • 很多人回复......我试过了......它在订单项上给了我以下错误消息。PostedByAvatar-------- string 'a.PostedByAvatar Anonymous Types:'一个是新的{字符串消息,int? PostedBy,字符串 PostedByName,字符串 PostedByAvatar,DateTime PostedDate,int PostId} 错误:属性或索引器“AnonymousType#1.PostedByAvatar”不能分配给---它是只读的
    • 对不起,但我必须问----------在 GetPosts 行--------PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),它的意思是 int? Post.PostedBy 错误:xxx.controller._GenerateAvatarUrlForUser(int)' 的最佳重载方法匹配有一些无效参数。我已将其从 UserId 更改为 Id,就像在我的数据库中一样,主键是 Id 但仍然是相同的消息
    • 显示你的Post 班级
    • 我上次发过有问题的帖子
    • 像魅力一样工作,非常感谢先生,我从过去两周就被困在其中了,先生,您现在救了我,我至少可以再次放松很多 thnxx 先生
    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2013-02-09
    相关资源
    最近更新 更多