[MVC]檔案上傳至資料庫

檔案上傳至資料庫

HttpPostedFileBase 有提供InputStream屬性,其型別是Stream。 所以很簡單就能將上傳的檔案轉換成bytes,就能輕易存入資料庫了。

View

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SingleFileUpload</title>
</head>
<body>
    <div>
        @*
            參數一:Action
            參數二:Controller
            參數三:Post方式送資料
            參數四:當表單元素有 <input type="file"> 設定 multipart/form-data,才可以檔案上傳
        *@
        @using (Html.BeginForm("FileUploadWithBytes", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <input type="file" name="file" />
            <br />
            <input type="submit" value="檔案上傳" />
        }
    </div>
    <div>
        @if (ViewBag.UploadedMessage != null)
        {
            <p style="color:green">
                @ViewBag.UploadedMessage
            </p>
        }
    </div>
</body>
</html>

Action

public ActionResult FileUploadWithBytes(HttpPostedFileBase file)
{
    if (file != null)
    {
        int length = file.ContentLength;

        byte[] buffer = new byte[length];

        // 使用InputStream屬性,將上傳的檔案寫入buffer
        file.InputStream.Read(buffer, 0, length);

        StoreFile sf = new StoreFile() 
        { 
            MimeType = file.ContentType,
            File = buffer
        };

        db.StoreFile.Add(sf);

        db.SaveChanges();

        //成功訊息
        ViewBag.UploadedMessage = "檔案上傳成功";
    }
    return View();
}

Model

[Table("StoreFile")]
public partial class StoreFile
{
    [Key]
    public long ID { get; set; }

    [Required]
    [StringLength(50)]
    public string MimeType { get; set; }

    [Required]
    public byte[] File { get; set; }
}

 

 

 

一天一分享,身體好健康。

該追究的不是過去的原因,而是現在的目的。