Monday, November 9, 2009

Upload Files to the server for different file types using vb.net



GoldMoney. The best way to buy gold & silver


Upload files to the server App helps the user upload different file to the Server.
This app allows you to upload all the file types except Exe and zip files.

asp:FileUpload control to upload files to server. When you click on the browse button.it opens the file dialog window and we can select file which we want to upload.

I have written UploadFiles() method this method mainly checks to see if we have really trying to upload the file or not, it also checks to see if file types and also checks the file size which should not be greater than 5mb.And finally saves the file to the server.

This condition is checking to see if there is any file selected to upload if not it displays that "There is no file to Upload

if ((UploadFile.PostedFile != null) && (UploadFile.PostedFile.ContentLength > 0))

This line of code actually checks the size of the file. UploadFile.PostedFile.ContentLength / 1048576 gives the actual size in MB.
'Checking for File Size in MegaBytes. 1048576 bytes represents 1 MB.

_fileSize value is hardcoded as 5 mb. You can make this value configurable.


if (((UploadFile.PostedFile.ContentLength / 1048576) <= this._fileSize))



This particular block of code checks the file types. It will not allow uploading EXE and zip file types to the server. It will allow only file types like text, PDF, MSWORD, JPG, EXCEL,POWER point. I have written jpg, jpeg, pjpeg because some browsers will take jep as pjpeg. So if you don't put the condition image/pipe and upload jpg or jpeg it will assume it as different file type and won’t allow the user to upload the file. So it better to have these 3 conditions.

if (UploadFile.PostedFile.ContentType == "text/plain" || UploadFile.PostedFile.ContentType == "application/pdf" || UploadFile.PostedFile.ContentType == "application/msword" || UploadFile.PostedFile.ContentType == "application/vnd.ms-excel" || UploadFile.PostedFile.ContentType == "application/vnd.ms-powerpoint" || UploadFile.PostedFile.ContentType == "image/jpg" || UploadFile.PostedFile.ContentType == "image/jpeg" || UploadFile.PostedFile.ContentType == "image/pjpeg")

After checking ther file types we are using Path.GetFullPath,Path.GetFileName to get the file name and file path.

SaveFile method save the file to the server. by using the file.SaveAs(savePath). Hope this blog will be use full for the developers. Any questions please post it. I will respond with the answer.



//Default.aspx
1)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>




Untitled Page


Upload Files to the Server.











//Code
using System;
using System.IO;
using System.Web;
using System.Xml;
using System.Web.UI;
using System.Net.Mail;
using Microsoft.VisualBasic;
using System.Web.SessionState;
using System.Web.UI.WebControls;

partial class _Default : System.Web.UI.Page
{
#region "Private Variables And Constants"
private string[] file;
private string fileName = string.Empty;
private string _fileTypes = string.Empty;
private string _serverpath = string.Empty;
string filePath = string.Empty;
private int _fileSize = 5;
#endregion

///
/// Upload files upload to the server
///

///
public void UploadFiles()
{
try
{
int fileTypeCounter = 0;
file = _fileTypes.Split(',');
if ((UploadFile.PostedFile != null) && (UploadFile.PostedFile.ContentLength > 0))
{
//Checking for File Size in MegaBytes. 1048576 bytes represents 1 MB.
if (((UploadFile.PostedFile.ContentLength / 1048576) <= this._fileSize)) { for (fileTypeCounter = 0; fileTypeCounter <= file.Length - 1; fileTypeCounter++) { file[fileTypeCounter] = file[fileTypeCounter].ToString(); if (!(UploadFile.PostedFile.ContentType == "application/octet-stream")) { if (!(UploadFile.PostedFile.ContentType == "application/zip")) { if (UploadFile.PostedFile.ContentType == "text/plain" || UploadFile.PostedFile.ContentType == "application/pdf" || UploadFile.PostedFile.ContentType == "application/msword" || UploadFile.PostedFile.ContentType == "application/vnd.ms-excel" || UploadFile.PostedFile.ContentType == "application/vnd.ms-powerpoint" || UploadFile.PostedFile.ContentType == "image/jpg" || UploadFile.PostedFile.ContentType == "image/jpeg" || UploadFile.PostedFile.ContentType == "image/pjpeg") { filePath = Path.GetFullPath(UploadFile.PostedFile.FileName); fileName = Path.GetFileName(UploadFile.PostedFile.FileName); SaveFile(UploadFile.PostedFile); } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "Only File type text,PDF,JPG,MSWord,Excel,PowerPoint are allowed."; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "You cannot upload file type Zip"; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "You cannot upload file type Zip"; } break; // TODO: might not be correct. Was : Exit For } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "The File size cannot be greater than 5mb"; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "There is no file to Upload"; } } catch (Exception ex) { lblErrorMsg.Text = ""; lblErrorMsg.Text = ex.Message; } } ///
/// Save File to the Server (upload)
///

/// ///
private void SaveFile(HttpPostedFile file)
{
try
{
// Specify the path to save the uploaded file to.
string savePath = null;
if (TextBox2.Text != null & TextBox1.Text != null)
{
savePath = "\\\\" + TextBox2.Text + " \\e$\\" + TextBox1.Text + "\\";
fileName = UploadFile.FileName;
string pathToCheck = savePath.ToString() + fileName.ToString();
string temperoryfileName = string.Empty;
if ((UploadFile.HasFile))
{
savePath += fileName;
file.SaveAs(savePath);
lblErrorMsg.Text = "";
lblErrorMsg.Text = "The File has been uploaded successfully.";
}
}
else
{
lblErrorMsg.Text = "";
lblErrorMsg.Text = "Please enter the correct ServerName or else there is no server name exists with that Name.";
}

}
catch (Exception ex)
{
lblErrorMsg.Text = "";
lblErrorMsg.Text = ex.Message;
}
}

protected void Page_Load(object sender, System.EventArgs e)
{
lblErrorMsg.Text = "";
}

protected void Button1_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("\\\\" + TextBox2.Text + " \\e$\\" + TextBox1.Text);
}

protected void btnuploadFile_Click1(object sender, EventArgs e)
{
UploadFiles();
}
}




No comments:

Post a Comment