Senin, 11 April 2016

Program Sederhana – Menyimpan File

Uul     13.50.00    


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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ 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">
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:)

0 komentar :

About Us

Pripunto (Bahasa Jawa) yang artinya "Bagaimana sih?" Dibuat dengan semangat untuk memberikan sharing informasi

Category

© 2016 pripunto. Designed by Bloggertheme9. Powered By Blogger | Published By Blogger Templates .