[ASP.NET]將上傳圖檔分成大小圖後存入資料庫

[ASP.NET]將上傳圖檔分成大小圖後存入資料庫

在開發網購系統時 , 要將上傳的圖檔先處理成大圖(商品明細)及小圖(貨架使用)

步驟如下:

1.將上傳的檔案分別用infraview另存成大圖及小圖

2.將大圖及小圖寫入DB

程式如下


Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Diagnostics

Public Class UpImage
    <Flags()> _
    Public Enum ImageSizeEnum
        Original = -1
        Big = 0
        Small = 1
    End Enum
    Private ReadOnly exeFile As String = "C:\\Program Files (x86)\\IrfanView\\i_view32.exe"
    Public Sub New()
    End Sub
    ''' <summary>
    ''' 設定上傳路徑
    ''' </summary>
    ''' <param name="source">網頁</param>
    ''' <param name="uploadtime">上傳時間</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetFilePath(ByVal source As System.Web.UI.Page, ByVal uploadtime As DateTime) As String
        Dim path As String = source.Server.MapPath("~/../Upload/CooperativeWeb/" & uploadtime.AddYears(-1911).ToString("yyy") & "/")
        Dim DirInfo As New DirectoryInfo(Path)
        If DirInfo.Exists = False Then
            Directory.CreateDirectory(path)
        End If
        Return path
    End Function
    ''' <summary>
    ''' 上傳檔案並更新
    ''' </summary>
    ''' <param name="source">網頁</param>
    ''' <param name="uploader">上傳的fileupload</param>
    ''' <param name="條碼號">條碼號</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function UploadFile(ByVal source As System.Web.UI.Page, ByVal uploader As FileUpload, ByVal 條碼號 As String) As String
        Dim fileOK As Boolean = False
        If uploader.HasFile Then
            Dim fileExtension As String = System.IO.Path.GetExtension(uploader.FileName).ToLower()
            Dim allowedExtensions As String() = {".jpg", ".gif", ".png", ".bmp", ".wmf"}
            For i As Integer = 0 To allowedExtensions.Length - 1
                If fileExtension = allowedExtensions(i) Then
                    fileOK = True
                End If
            Next
        End If
        If fileOK Then
            Try
                Dim productinfo As New Product()
                Dim fileExtension As String = System.IO.Path.GetExtension(uploader.FileName).ToLower()
                Dim sep As String() = New String() {"\"}

                Dim destFileFullPath As String = GetFilePath(source, DateTime.Now) + GetUploadFileName(uploader, ImageSizeEnum.Original)
                Dim destFileFullPathBig As String = GetFilePath(source, DateTime.Now) + GetUploadFileName(uploader, ImageSizeEnum.Big)
                Dim destFileFullPathSmall As String = GetFilePath(source, DateTime.Now) + GetUploadFileName(uploader, ImageSizeEnum.Small)
                uploader.PostedFile.SaveAs(destFileFullPath)
                '用infraview產生大圖及小圖
                Process.Start(exeFile, " " & destFileFullPath & " /resize=(400,400) /aspectratio /resample /convert=" & destFileFullPathBig)
                Process.Start(exeFile, " " & destFileFullPath & " /resize=(150,150) /aspectratio /resample /convert=" & destFileFullPathSmall)
                '停三秒等大圖跟小圖生完成
                System.Threading.Thread.Sleep(3000)

                Dim filestreamBig() As Byte = GetImageBytes(destFileFullPathBig)
                Dim filestreamSmall() As Byte = GetImageBytes(destFileFullPathSmall)
                '將圖檔寫入資料庫
                Return productinfo.更新上架資料圖片(條碼號, filestreamBig, filestreamSmall)

            Catch ex As Exception
                'return "上傳失敗!請勿重覆上傳";
                Return ex.ToString()
            End Try
        Else
            Return "請上傳正確檔案類型圖檔(.jpg,.gif,.png,.bmp,.wmf!)"
        End If
    End Function
    ''' <summary>
    ''' 取得檔名
    ''' </summary>
    ''' <param name="uploader"></param>
    ''' <param name="imsize"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetUploadFileName(ByVal uploader As FileUpload, ByVal imsize As ImageSizeEnum) As String
        If uploader.HasFile = False Then
            Return String.Empty
        Else
            Dim filename As String = uploader.FileName.Replace(System.IO.Path.GetExtension(uploader.FileName).ToUpper(), String.Empty).Replace(System.IO.Path.GetExtension(uploader.FileName).ToLower(), String.Empty)
            Dim fileExtension As String = System.IO.Path.GetExtension(uploader.FileName).ToLower()
            Return filename & imsize.ToString() & DateTime.Now.ToString("yyyyMMddHHmmss") & fileExtension

        End If
    End Function    
    ''' <summary>
    ''' 取得檔案內容(大圖及小圖)
    ''' </summary>
    ''' <param name="filepath">檔案路徑</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetImageBytes(ByVal filepath As String) As Byte()
        Dim mBinaryAry() As Byte
        Dim fs As IO.FileStream
        Try
            fs = IO.File.OpenRead(filepath)
            ReDim mBinaryAry(CInt(fs.Length - 1))
            '用 Read 方法將部份或全部的資料複製到某 Byte 陣列中
            fs.Read(mBinaryAry, 0, CInt(fs.Length))
            '根據 Byte 陣列建立 MemoryStream 物件
            Dim bf As New IO.MemoryStream(mBinaryAry)
            Return bf.ToArray()
        Catch ex As Exception
            Return Nothing
        Finally
            If Not fs Is Nothing Then
                fs.Close()
            End If
        End Try

    End Function
    ''' <summary>
    ''' 從資料欄位(datatype:image)取得影像資料
    ''' </summary>
    ''' <param name="datarow">Datarow</param>
    ''' <param name="columnname">欄位名稱</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetImageFromDb(ByVal datarow As DataRow, ByVal columnname As String) As Byte()
        Dim bf As New IO.MemoryStream(CType(datarow(columnname), Byte()))
        Return bf.ToArray()
    End Function

End Class

寫入的sql組成如下


        Dim cmdtext As String = "update 上架資料 "
        cmdtext &= "set 圖片=@圖片 "
        cmdtext &= ",縮圖=@縮圖 "
        cmdtext &= " where 條碼號=@條碼號 and ((上架狀態='3' AND 下架狀態 <> '3') AND (下架時間 > GETDATE() or 下架時間 is null))"
        Dim sqlparam As New List(Of SqlParameter)
        sqlparam.Add(New SqlParameter("條碼號", System.Data.SqlDbType.VarChar))
        sqlparam.Add(New SqlParameter("圖片", System.Data.SqlDbType.Image))
        sqlparam.Add(New SqlParameter("縮圖", System.Data.SqlDbType.Image))
        sqlparam(0).Value = 條碼號
        sqlparam(1).Value = 圖片
        sqlparam(2).Value = 縮圖
        Return dal.NonQueryResultTranc(cmdtext, sqlparam.ToArray())
    End Function

用法如下


                Dim upimages As New UpImage()
                upimages.UploadFile(Me, FileUpload1, txtBarcode.Text.Trim())