简体   繁体   English

如何在Visual Studio 2012的(数据库)表中手动存储图像并在ASP.NET MVC中使用jquery ajax进行检索

[英]How to manually store image in (database) table in visual studio 2012 and retrieve using jquery ajax in asp.net mvc

My database table 我的数据库表

First I tried storing images with datatype image/varbinary but it is giving error: 首先,我尝试存储数据类型为image / varbinary的图像,但出现错误:

"Invalid Value The changed value in this cell was not recognized as being valid. .Net Framework Data Type: Byte[] Error Message: You cannot use the result pane to set this Field data to values other than NULL Type a value appropriate for the data type or press ESC to cancel the change". “无效值此单元格中更改的值未被识别为有效。.NetFramework数据类型:Byte []错误消息:您不能使用结果窗格将此字段数据设置为NULL以外的值。数据类型或按ESC取消更改”。

How can I store image in my database table manually and retireve them through jquery ajax method. 如何将图像手动存储在数据库表中,并通过jquery ajax方法撤消它们。

use in C# Button Submit with data source 在C#按钮中使用随数据源一起提交

   if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != null)
            {
            byte[] img = new byte[Request.Files[0].ContentLength];
            Request.Files[0].InputStream.Read(img, 0, Request.Files[0].ContentLength);
            datasource.Photo = img; --here you can save file to Database
            }

for retrieving image from dbserver use belowed 用于从dbserver检索图像的方法如下

img.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(Upprofile.Photo);

Have you ever tried other ways to store images ? 您是否尝试过其他方式存储图像?
I have never used such a way to store image in database if you want my two cents it would be better to save your image on host and save its url in the database. 如果您想要我的两美分,我从未使用过这种在数据库中存储图像的方法,最好将图像保存在主机上并将其url保存在数据库中。 You only need url to show picture in browser...! 您只需要url即可在浏览器中显示图片...!

I'm not sure if this works in VS2012, but you can try this approach that I'm using in my MVC projects: 我不确定这是否适用于VS2012,但是您可以尝试在MVC项目中使用的这种方法:

public action UploadFile(HttpPostedFileBase file) //this is how you get the file that was submited from your form
{
    //so now that I have the file, i need to save it somewhere
    //let's see if we have a folder for that, if not let's create it

    if(!Directory.Exists(Server.MapPath("~/The path from the root of the app to the uploaded files folder/")))
    {
        Directory.CreateDirectory(Server.MapPath("~/The path from the root of the app to the uploaded files folder/"));
    } //the ~ symbol is part of the code, it returns the physical path to the root of the application
    var storage = Server.MapPath("~/The path from the root of the app to the uploaded files folder/");

    //now we need a name, we can generate one as a GUID for example, or we can get it's own.

    var fileName = file.FileName.Substring(file.FileName.LastIndexOf("\"), file.Name.Length + 1);

    //Now you might have to play a bit with the substring arguments, I'm not sure i wrote that right, 
    //it might not need the +1 part, or it might need it on the LastIndexOf as well, 
    //anyway, now we have the name and the folder where to save our file, let's do that:

    path = String.Format("{0}\{1}", storage, filename);
    try
    {
        file.SaveAs(path); //Now the file is on the server, 
        //just save this path and whatever else you need in the database so you can
        //grab it later.
    } 
    catch 
    {
        //do your exception handling here
    }

    Saving to database here...
}

In order to grab it you just get that object from the database like any other objects like so: 为了抓取它,您只需像其他对象一样从数据库中获取该对象,如下所示:

Let's presume you're doing everything in your controller, which you shouldn't, 假设您正在控制器中做所有不应该做的事情,

public Action GetFile(int id)
{
    using(context = new YourDbContext())
    {
        var file = context.Files.FirstOrDefault(p => p.Id == id);
    }
    return View(file);
}

And put it's path for the src in html to show the image like so: 并以html格式显示src的路径,如下所示:

<img src="@Model.path" /> //Considering that in your controller you will `return View(file);` 
//So your file object is the model.

One more thing, I'm not sure if in paths you'll need \\ or /, I always get it wrong the first time so debug it on the first run and if your path looks like Folder1Folder2Folder3File it means you need to change it :). 还有一件事,我不确定在路径中是否需要\\或/,我总是第一次出错,因此请在第一次运行时对其进行调试,如果您的路径看起来像Folder1Folder2Folder3File则意味着您需要更改它: )。

I hope this helped, good luck. 希望这对您有帮助,祝您好运。

PS, there might be better ways to do it, but this is how I'm doing it and it seams to work fine for me. PS,也许会有更好的方法来做到这一点,但这就是我正在做的事情,它对我来说工作正常。

On server, you convert image to a base64 string and save to database. 在服务器上,将图像转换为base64字符串并保存到数据库。

using (Image image = Image.FromFile(Path))
{                 
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }                  
}

Beside Client, you put base64 string in Image object 在客户端旁边,将base64字符串放入Image对象

var image = new Image();
image.src = 'data:image/png;base64,your base64 string';
document.body.appendChild(image);

I think store image on the disk better. 我认为将映像存储在磁盘上更好。

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

相关问题 如何在Visual Studio 2012上使用ASP.NET(包含MVC)C#配置或设置Log4Net - How to configure or setup Log4Net with ASP.NET ( included MVC) C# on Visual Studio 2012 ~ ~ 使用asp.net Web表单Visual Studio 2012将图像插入Oracle数据库 - insert image into oracle database with asp.net web forms visual studio 2012 图像未在ASP.net visual studio 2012中显示 - Image not showing in ASP.net visual studio 2012 如何在Visual Studio 2012中为ASP.NET MVC 4配置Microsoft.Owin.Security.Google? - How to configure Microsoft.Owin.Security.Google for ASP.NET MVC 4 in Visual Studio 2012? 如何在Visual Studio 2012上查看ASP.NET MVC移动页 - How to view an ASP.NET MVC mobile page on Visual Studio 2012 使用Visual Studio 2012将具有数据库的ASP.net Web应用程序发布到Azure - Publishing ASP.net web application with database to Azure using Visual Studio 2012 使用Visual Studio 2012的Asp.Net网站中未显示背景图像 - Background Image Not Appearing in Asp.Net Site Using Visual Studio 2012 使用Visual Studio 2012在ASP.NET上运行WPF应用程序 - Run WPF application on ASP.NET using Visual Studio 2012 如何在ASP.NET MVC中使用jQuery / Ajax将数据插入数据库? - How to insert data into a database using jQuery / Ajax in ASP.NET MVC? 如何在asp.net中使用jQuery Ajax从数据库加载图像 - How to load image from database using jquery ajax in asp.net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM