【问题标题】:how to store image in sql using stored procedure? [closed]如何使用存储过程将图像存储在sql中? [关闭]
【发布时间】:2012-06-23 10:36:27
【问题描述】:

在我的网页中,图片是从文件上传控件获取的,它必须存储在sql server中。如何编写存储过程以将图像保存在sql server中?

【问题讨论】:

  • 到目前为止你做了什么??

标签: asp.net sql sql-server stored-procedures


【解决方案1】:

一些示例代码(未经测试,可能需要一些修复):

CREATE PROCEDURE SaveFile(@id int, @file varbinary(max)) AS

INSERT INTO MyFiles VALUES(@id, @file)
GO

在 .NET 代码中:

SqlCommand comm = new SqlCommand(@"SaveFile")
comm.CommandType = CommandType.StoredProcedure;

SqlParameter id = new SqlParameter("int", SqlDbType.Int);
id.value = 1; // some id

FileStream fileStream = ... your file;
byte[] buf = new byte[fileStream.length];
fileStream.Read(buf, 0, buf.length);
SqlParameter file = new SqlParameter("@file", SqlDbType.VarBinary, buf.Length);
file.Value = buf;

comm.Parameters.Add(id)    
comm.Parameters.Add(file)

comm.Execute();

【讨论】:

  • 如何检索该图像并显示在某个地方?
  • 如何显示该图片?在面板 r wat??请指导我..
  • 问题是关于将图像存储在数据库中。我认为它已经得到了回答。怎么显示图片?由您决定使用什么 UI 元素以及如何使用。通常要读取图像 - 按照相反的顺序进行操作。从表中选择文件; fileStream.Write(buf);但是,您可能需要创建一个动态页面来读取图像并将其返回,同时牢记 Content-Type。
【解决方案2】:

只需使用通常的存储过程,只需使用不同的数据类型,将其保存为字节数组,因此您必须先将图像转换为字节数组,然后再将其作为参数传递给您的存储过程,保存长度和文件类型也是。

这是一个示例存储过程。我会把剩下的留给你。如果您知道如何在 Web 应用程序中执行查询,则可以调用此过程。只需谷歌即可。

USE [mydatabasename]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[myprocedurename]

    @ImageFile image,
    @FileType nvarchar(10),
    @FileSize int
AS
-- INSERT a new row in the table.
INSERT [dbo].[mytablename]
(
    [ImageFile],
    [FileType ],
    [FileSize ]
)
VALUES
(
    @ImageFile,
    @FileType,
    @FileSize
)
-- Get the IDENTITY value for the row just inserted.
SELECT @ImageId=SCOPE_IDENTITY()

我猜图像文件类型将会过时,所以你应该使用不同的文件类型来保存你的字节

【讨论】:

  • 你能给我asp.net和存储过程的编码吗???
  • 如何检索该图像并显示在某个地方?
  • 如何显示该图片?在面板 r wat??请指导我..
  • 首先你必须检索字节数组,然后使用http内容响应显示它
猜你喜欢
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
相关资源
最近更新 更多