【问题标题】:stuck while uploading image file in sql server though vb.net通过vb.net在sql server中上传图像文件时卡住了
【发布时间】:2010-01-27 21:34:34
【问题描述】:

重新发布相同的问题,因为发布后,无法编辑问题。如果你之前读过这个问题,请特别阅读底部 -

好的,这是我从这个站点使用的代码。一切正常,但我需要一些不同的代码来上传图片,而且我不知道该怎么做 - 这是代码 -

Private Sub btnAttach_Click(ByVal sender As System.Object, _  
ByVal e As System.EventArgs) Handles btnAttach.Click  
    Dim iLength As Integer = CType(File1.PostedFile.InputStream.Length, Integer)  
    If iLength = 0 Then Exit Sub 'not a valid file  
    Dim sContentType As String = File1.PostedFile.ContentType  
    Dim sFileName As String, i As Integer  
    Dim bytContent As Byte()  
    ReDim bytContent(iLength) 'byte array, set to file size  

'strip the path off the filename  '
i = InStrRev(File1.PostedFile.FileName.Trim, "\")  
If i = 0 Then  
    sFileName = File1.PostedFile.FileName.Trim  
Else  
    sFileName = Right(File1.PostedFile.FileName.Trim, Len(File1.PostedFile.FileName.Trim) - i)  
End If  

Try  
    File1.PostedFile.InputStream.Read(bytContent, 0, iLength)  
    With cmdInsertAttachment  
        .Parameters("@FileName").Value = sFileName  
        .Parameters("@FileSize").Value = iLength  
        .Parameters("@FileData").Value = bytContent  
        .Parameters("@ContentType").Value = sContentType  
        .ExecuteNonQuery()  
    End With  
Catch ex As Exception  
    'Handle your database error here  
    dbConn.Close()  
End Try  
Response.Redirect(Request.Url.ToString) 'Refresh page 
End Sub  

一切正常,除了这部分 -

With cmdInsertAttachment  
    .Parameters("@FileName").Value = sFileName  
    .Parameters("@FileSize").Value = iLength  
    .Parameters("@FileData").Value = bytContent  
    .Parameters("@ContentType").Value = sContentType  
    .ExecuteNonQuery()  
End With  

我没有使用 cmdinsertattachment。我正在使用 HTML 工具箱中的 Html - Input(File)。输入文件的 ID 为 ID="upldimg"。

那么我如何将它插入到我的表中 -

Column1 ID identity
Column2 Img image
Column 3 Description varchar(200).

请告诉我插入语句 -

INSERT into table1 (Img, Description) values (???, txtdescription.text)

我在插入语句中做 upldimg.text 吗?

【问题讨论】:

标签: sql-server vb.net image


【解决方案1】:
  1. 使用适当的数据类型。 IMAGE 已弃用,请改用 VARBINARY(MAX)
  2. 不要为任意大小的图像分配字节数组。使用块。
  3. 不要阻止等待整个文件的数据库上传的响应。

如果我这样做,我会使用 IIS 模块来处理文件的分块同时在 HTTP 请求中接收,以避免完全创建临时文件。非常简单的方法如下所示:

create table Uploads (
  Id int identity(1,1) primary key
  , FileName varchar(256)
  , ContentType varchar(256)
  , FileData varbinary(max)); 

和aspx:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack && FileUpload1.HasFile)
        {
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(TransferToDatabase), FileUpload1);
        }
    }

    protected void TransferToDatabase(object args)
    {
        try
        {
            Debug.Assert(args is FileUpload);
            FileUpload upload = (FileUpload)args;
            using (SqlConnection conn = new SqlConnection(
                Settings.Default.connString))
            {
                conn.Open();
                using (SqlTransaction trn = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand(@"
INSERT INTO Uploads(FileName, ContentType, FileData)
VALUES (@FileName, @ContentType, @initialChunk);
SET @id = SCOPE_IDENTITY();", conn, trn);
                    cmd.Parameters.AddWithValue("@FileName", upload.PostedFile.FileName);
                    cmd.Parameters.AddWithValue("@contentType", upload.PostedFile.ContentType);
                    SqlParameter paramId = new SqlParameter("@id", SqlDbType.Int);
                    paramId.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(paramId);

                    byte[] chunk = new byte[4096];
                    int offset = upload.FileContent.Read(chunk, 0, 4096);
                    byte[] initialChunk = chunk;
                    if (offset < 4096)
                    {
                        // can't pass only part of a byte[] as parameter value
                        // must copy out the appropiate size
                        initialChunk = new byte[offset];
                        Array.Copy(chunk, initialChunk, offset);
                    }
                    cmd.Parameters.AddWithValue("@initialChunk", initialChunk);
                    cmd.ExecuteNonQuery();

                    // Add the rest of the data
                    if (offset == 4096)
                    {
                        SqlParameter paramChunk = new SqlParameter("@chunk", SqlDbType.VarBinary, 4096);
                        SqlParameter paramLength = new SqlParameter("@length", SqlDbType.BigInt);
                        SqlCommand cmdAddChunk = new SqlCommand(@"
UPDATE Uploads
   SET FileData.Write(@chunk, NULL, @length)
WHERE id = @id", conn, trn);
                        cmdAddChunk.Parameters.AddWithValue("@id", paramId.Value);
                        cmdAddChunk.Parameters.Add(paramChunk);
                        cmdAddChunk.Parameters.Add(paramLength);

                        do
                        {
                            int chunkSize = upload.FileContent.Read(chunk, 0, 4096);
                            if (0 == chunkSize)
                            {
                                break;
                            }
                            paramChunk.Value = chunk;
                            paramLength.Value = chunkSize;

                            cmdAddChunk.ExecuteNonQuery();

                            offset += chunkSize;

                        } while (true);
                    }

                    trn.Commit();
                }
            }
        }
        catch (Exception e)
        {
            // Log to the appropiate error logging infrastructure
            Debug.Write(e);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2018-01-21
    相关资源
    最近更新 更多