Program Sederhana – Menyimpan File


upload

Kali ini penulis mencoba share sedikit tentang program sederhana untuk menyimpan file (gif/ jpeg/ png/ pdf) ke dalam database. Juga untuk menampilkannya dari file yang sudah tersimpan ke dalam database.

Langsung saja, berikut source codenya :

Keterangan :

- Programming language : csharp

- Database : SQL Server 2008

1. UploadFile.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadFile.aspx.cs" Inherits="UploadFile" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Upload-View File</title>
</head>
<body>
    <form id="form1" runat="server">
    <h1>Upload-View File</h1>
    <span>*) Image (gif/ jpeg/ png)</span>
    <br />
    <span>*) File (pdf)</span>
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
    <table>
        <tr>
            <td>Upload</td>
        </tr>
        <tr>
            <td>Title</td>
            <td><asp:TextBox ID="txtTitleUpload" runat="server" MaxLength="10"></asp:TextBox></td>
        <tr>
            <td>File</td>
            <td>
                <asp:FileUpload ID="fuFile" runat="server" />
                <asp:Button ID="btnUpload" runat="server" Text="Upload"
                    onclick="btnUpload_Click"/>
            </td>
        </tr>

        </tr>
    </table>
    <br />
    <br />
    <table>
        <tr>
            <td>View</td>
        </tr>
        <tr>
            <td>Title</td>
            <td>
                <asp:TextBox ID="txtTitleView" runat="server" MaxLength="10"></asp:TextBox>
                <asp:Button ID="btnView" runat="server" Text="View" onclick="btnView_Click"/>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

2. UploadFile.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class UploadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void setKomponen(string message)
    {
        txtTitleUpload.Text = "";
        txtTitleView.Text = "";
        if (message != string.Empty)
        {
            lblMessage.Text = string.Format("File upload : {0} success", message);
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            FileUpload fuFile = (FileUpload)this.FindControl("fuFile");
            if (fuFile.PostedFile == null || string.IsNullOrEmpty(fuFile.PostedFile.FileName) || fuFile.PostedFile.InputStream == null)
            {
                lblMessage.Text = "Please Upload Valid picture file";
                return;
            }
            string extension = System.IO.Path.GetExtension(fuFile.PostedFile.FileName).ToLower();
            string MIMEType = null;
            switch (extension)
            {
                case ".gif":
                    MIMEType = "image/gif";
                    break;
                case ".jpg":
                case ".jpeg":
                case ".jpe":
                    MIMEType = "image/jpeg";
                    break;
                case ".png":
                    MIMEType = "image/png";
                    break;
                case ".pdf":
                    MIMEType = "application/pdf";
                    break;
                default:
                    lblMessage.Text = "Not a Valid file format";
                    return;
                    break;
            }
            using (SqlConnection sConn = new SqlConnection([your sql connection string]))
            {
                string query = "INSERT INTO M_FILES (TITLE, MIME_TYPE, [FILE]) VALUES (@TITLE, @MIME_TYPE, @FILE)";
                SqlCommand sComm = new SqlCommand(query, sConn);
                sComm.Parameters.AddWithValue("@TITLE", txtTitleUpload.Text.Trim());
                sComm.Parameters.AddWithValue("@MIME_TYPE", MIMEType);
                byte[] fileBytes = new byte[fuFile.PostedFile.InputStream.Length + 1];
                fuFile.PostedFile.InputStream.Read(fileBytes, 0, fileBytes.Length);
                sComm.Parameters.AddWithValue("@FILE", fileBytes);
                sConn.Open();
                sComm.ExecuteNonQuery();
                sConn.Close();
            }
            setKomponen(txtTitleUpload.Text.Trim());
        }
        catch (Exception exp)
        {
            lblMessage.Text = "Error upload file : " + exp.Message;
        }
    }

    protected void btnView_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection sConn = new SqlConnection([your sql connection string]))
            {
                string query = "SELECT [FILE], MIME_TYPE FROM M_FILES WHERE TITLE =@TITLE";
                SqlCommand sComm = new SqlCommand(query, sConn);
                sComm.Parameters.AddWithValue("@TITLE", txtTitleView.Text.Trim());
                sConn.Open();
                SqlDataReader sReader = sComm.ExecuteReader();
                DataTable dt = new DataTable();
                if (sReader.HasRows)
                {
                    dt.Load(sReader);
                }
                byte[] fileByte = (byte[])dt.Rows[0]["FILE"];
                string content = dt.Rows[0]["MIME_TYPE"].ToString();
                sConn.Close();
                Response.ContentType = content;
                Response.BinaryWrite(fileByte);
                Response.End();
            }
        }
        catch (Exception exp)
        {
            lblMessage.Text = "Error upload file : " + exp.Message;
        }
    }
}

3. Database

Database name : Sample

USE [Sample]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[M_FILES](
	[FILE_ID] [int] IDENTITY(1,1) NOT NULL,
	[TITLE] [varchar](10) NOT NULL,
	[CREATED_DATE] [datetime] NOT NULL,
	[MIME_TYPE] [varchar](50) NOT NULL,
	[FILE] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[M_FILES] ADD  CONSTRAINT [DF_M_FILE_CREATED_DATE]  DEFAULT (getdate()) FOR [CREATED_DATE]
GO

Hasil eksekusi programnya tampak seperti di bawah ini :

upload file

Demikian share kali ini, semoga bermanfaat :)

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s