=================================
=================================
=================================
File Upload control in C# as a friendly web user control. Easy upload, delete, and view options
C# asp.net 파일 컨트롤 - 업로드, 삭제 생성, 수정
자료가 너무 좋아서 반햇심. 쫍쫍
The Source Code:
using System;
using System.Web;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.IO;
public partial class Controls_FileUpload : System.Web.UI.UserControl
{
private string SaveToPath = "";
private string VirtualPath = "";
#region File Upload Control Properties
/// <summary>
/// Save Location of File. Example "C:\TEMP\"
/// </summary>
[Browsable(true), Category("Properties"), Description("Save Location of File")]
public string File_Save_Path
{
get
{
return SaveToPath;
}
set
{
SaveToPath = value;
}
}
/// <summary>
/// Virtual Path of document. Example: "http://servername/filedirpath/"
/// </summary>
[Browsable(true), Category("Properties"), Description("Virtual Path of document")]
public string Virtual_Path
{
get
{
return VirtualPath;
}
set
{
VirtualPath = value;
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
this.lblError.Text = "";
if (!Page.IsPostBack)
{
if (this.VirtualPath.Length == 0)
{
this.lblError.Text = "Virtual Path Property has not been set.";
this.Panel_Control.Enabled = false;
return;
}
else if (this.SaveToPath.Length == 0)
{
this.lblError.Text = "Save To Path Property has not been set.";
this.Panel_Control.Enabled = false;
return;
}
else
{
if (ValidatePath() == true)
{
if (ShowAllFiles() == false)
{
//An error occured.
this.Panel_Control.Enabled = false;
return;
}
}
else
{
this.Panel_Control.Enabled = false;
return;
}
}
}
}
/// <summary>
/// Validates if the Path exists. If it doesn't we try to create it.
/// </summary>
private bool ValidatePath()
{
try
{
if (System.IO.Directory.Exists(SaveToPath) == false)
{
System.IO.Directory.CreateDirectory(SaveToPath);
return true;
}
else
{
return true;
}
}
catch (Exception ex)
{
lblError.Text = "Error: " + ex.Message.ToString();
return false;
}
}
/// <summary>
/// Shows all the files in this directory.
/// </summary>
private bool ShowAllFiles()
{
try
{
//Clear the list box
lstDocs.Items.Clear();
//Get all the directory files
string[] subfiles = Directory.GetFiles(SaveToPath);
foreach (string file_obj in subfiles)
{
string doc_name = System.IO.Path.GetFileName(file_obj);
//text is document name
//value is full path to document
ListItem tempItem = new ListItem(doc_name, file_obj);
//add to list box
lstDocs.Items.Add(tempItem);
}
return true;
}
catch (Exception ex)
{
this.lblError.Text = "Error: " + ex.Message.ToString();
return false;
}
}
/// <summary>
/// Upload File
/// </summary>
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
if (filePSE.PostedFile.FileName == "" || filePSE.PostedFile.ContentLength == 0)
{
return;
}
string path = filePSE.PostedFile.FileName;
string doc_name = System.IO.Path.GetFileName(path);
string err = "";
bool isSafeFile = CheckExtensions(doc_name);
if (isSafeFile == false)
{
return;
}
if (System.IO.File.Exists(SaveToPath + doc_name))
{
this.lblError.Text = "A file with this name already exists.";
return;
}
filePSE.PostedFile.SaveAs(SaveToPath + doc_name);
//Create list item with text as document name
//and value as full path
ListItem item = new ListItem(doc_name, SaveToPath + doc_name);
//add to list box
lstDocs.Items.Add(item);
this.lblError.Text = "File uploaded successfully.";
}
catch (Exception ex)
{
Response.Write("Error Uploading File: " + ex.Message.ToString());
Response.End();
}
}
/// <summary>
/// Delete File
/// </summary>
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (this.lstDocs.Items.Count == 0)
{
lblError.Text = "No items to delete";
return;
}
else if (this.lstDocs.SelectedIndex == -1)
{
lblError.Text = "Please select an item to delete";
return;
}
else
{
//get temp of selected item
string path = lstDocs.SelectedItem.Value;
//delete the file
System.IO.File.Delete(path);
//Remove list item
lstDocs.Items.Remove(lstDocs.SelectedItem);
this.lblError.Text = "File deleted successfully.";
}
}
catch(Exception ex)
{
Response.Write("Error Deleting File: " + ex.Message.ToString());
Response.End();
}
}
/// <summary>
/// Check if it part of allowed extensions
/// </summary>
private bool CheckExtensions(string filename)
{
try
{
/*
if ( (filename.ToLower().LastIndexOf(".doc") == -1) &&
(filename.ToLower().LastIndexOf(".pdf") == -1) &&
(filename.ToLower().LastIndexOf(".ppt") == -1) &&
(filename.ToLower().LastIndexOf(".txt") == -1) &&
(filename.ToLower().LastIndexOf(".xls") == -1) )
*/
if ((filename.ToLower().LastIndexOf(".exe") != -1))
{
this.lblError.Text = "This type of file cannot be uploaded.";
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message.ToString());
Response.End();
//The line below will never execute.
return false;
}
}
/// <summary>
/// Checks if we have any items, and if so generates javascript for double click.
/// </summary>
protected override void OnPreRender(EventArgs e)
{
if (lstDocs.Items.Count > 0)
{
/*
if you want to alert the value for error checking, use the following:
this.lstDocs.Attributes["ondblclick"] = "alert(this.options[this.selectedIndex].text); window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";
instead of
*/
this.lstDocs.Attributes["ondblclick"] = "window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";
}
else
{
this.lstDocs.Attributes.Remove("ondblclick");
}
base.OnPreRender(e);
}
}
=================================
=================================
=================================
'프로그래밍 관련 > 웹' 카테고리의 다른 글
쿠키정보 보기 (0) | 2020.09.10 |
---|---|
html에서 asp나 그밖의 문법을 사용할 수있도록 IIS설정하기 (0) | 2020.09.10 |
HTML WEB 웹 개발 각각 cache 유무 코드의 no-cache 캐시삭제, browser 가 caching 하지 않게 하는 http header 설정 (0) | 2014.11.27 |
IIS6에서 asp 업로드 및 다운로드 제한설정 (0) | 2011.03.30 |
ASP DB Connect(연결) 할때 오류나는 경우 확인법 또는 구성 설정법 (0) | 2010.01.14 |
댓글 영역