Google+ Followers

Tuesday, June 18, 2013

Multiple Image Upload In One Time example in ASP.NET


I will explain how to upload multiple files in using uploadify plugin in JQuery.

We can implement this concept by using uploadify plugin with few simple steps.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="New_uploadphoto.aspx.vb" Inherits="New_uploadphoto" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<title>Photo Upload</title>
<script type="text/javascript" src="../UploadMultiPhoto/jquery.uploadify-3.1.js"></script>

<link href="../Css/Socialnetwork.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../UploadMultiPhoto/jquery-notes_1.0.8.js"></script>
<link href="../UploadMultiPhoto/style.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
$(function() {
'removeCompleted' : false,
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png',
'buttonText':'SELECT PHOTOS',
'swf' : '../UploadMultiPhoto/uploadify.swf',
'uploader' : '../UploadMultiPhoto/handler.ashx?UserID=<%= CommonClass.EncryptText(CommonClass.getCustomerID()) %>&Album=<%= CommonClass.EncryptText(ViewState("AlbumName"))%>',
'onUploadSuccess' : function(file, data, response) {
var dat = $.parseJSON(data);
var str='<div style="width: 320px;">'+
'<div class="floatL" style="position:relative;">' +
'<div class="floatL" style="width:320px;">' +
'<center><img class="test' + dat[0]["PhotoNo"] + '" src="' + dat[0]["path"] + '"></center>' +
'</div>' +
'</div>' +
'<div class="floatL" style="margin-top: -15px;">' +
'<div class="floatL" style="width: 250px;">' +
'Photo Description:</div>' +
'<div style="margin-top:4px; float:Left;"><textarea onchange=SavePhotoDes(this.value,"' + dat[0]["PhotoNo"] + '") style="width:310px"></textarea></div>' +
'</div>' +
var availableTags;
function SavePhotoDes(a,b){
url: "JSONData.aspx?mode=34",
dataType: "JSON",
data:{PhotoNumber:b,Value:a,AlbumName:'<%= CommonClass.EncryptText(ViewState("AlbumName")) %>'},
success: function (data) {
function BindTag(no){
$('.test' + no).jQueryNotes({
minWidth: 20,
minHeight: 20,
aspectRatio: true,
helper: 'helper-class',
allowLink: false,
dateFormat: 'D.M.Y',
operator: '../Customer/JSONData.aspx?mode=16&albumid=<%=ViewState("albumid") %>&PhotoID=' +no ,
allowEdit: false,
allowAdd: true,
allowAuthor: false,
allowDelete: false
url: "JSONData.aspx?mode=17",
dataType: "JSON",
data:{albumid:'<%=ViewState("albumid") %>',frdid:0},
success: function (data) {
availableTags = data;


<link rel="stylesheet" type="text/css" href="../UploadMultiPhoto/uploadify.css" />
<style type="text/css">
.uploadify-queue-item .cancel a{
.submitBtn {
background: none repeat scroll 0 0 #EAEAEA;
border: 1px solid #C3C2C2;
color: #666666;
font-size: 11px;
padding: 2px 10px 3px;
text-align: center;
.ui-menu .ui-menu-item
width: 146px;
.ui-menu .ui-menu-item a
font-family: Tahoma,Verdana,Arial,sans-serif;
font-size: 12px;
line-height: 1;
max-height: 100px; /*height: 200px;*/
overflow-y: auto;
overflow-x: hidden;
background-color: #fff;
<form id="Form2" method="post" runat="server">
<div id="container" class="mainContainer">
<div style="width: 1004px; float: left;min-height:550px;">
<div class="floatL" style="margin-top:50px; position:relative; width:100%; margin-left:10px;">
<input type="file" name="file_upload" id="file_upload" />
<div class="floatL" style="position:absolute; top:11px; left:140px; font-size:11px;">Double click on the images to tag friends</div>
<asp:LinkButton ID="lnkUploadPhoto" runat="server" style="display:none;">
<div style="font-size:10px; margin:15px 0 0 82%;" class="floatL submitBtn"><b>Upload Photos</b></div>
<asp:LinkButton ID="lnkCancel" runat="server" PostBackUrl="../Customer/AlbumList.aspx" style="display:none;">
<div style="font-size:10px; margin:15px 0 0 1%;" class="floatL submitBtn"><b>Cancel</b></div>
<br style="clear:both;" />


If you observe above code in header section I added some of css and script files those files you can get it from attached folder or you can get it from here uploadify plugin and if you observe in uploadify function I used Handler.ashx in this we will write the code to upload files in folder for that Right click on your application >> Select Add New Item >> Select Generic Handler file and Give name as Handler.ashx >> Click OK
Open Handler.ashx file and write the following code 

VB.NET Code:  
<%@ WebHandler Language="VB" Class="Handler" %>

Imports System
Imports System.Web
Imports System.IO
Imports System.Web.Mail
Imports System.Web.SessionState

Public Class Handler : Implements IHttpHandler, IReadOnlySessionState
Private ReadOnly js As New Script.Serialization.JavaScriptSerializer()

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.AddHeader("Pragma", "no-cache")
'context.Response.AddHeader("Cache-Control", "private, no-cache")
End Sub
Public Sub HandleMethod(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "POST"
End Select
End Sub
Private Shared Function GivenFilename(ByVal context As HttpContext) As Boolean
Return Not String.IsNullOrEmpty(context.Request("f"))
End Function
Public Sub UploadFile(ByVal context As HttpContext)
If context.Request.Files.Count > 0 Then
Dim files As HttpPostedFile = context.Request.Files(0)
Dim AlbumNAme As String = CommonClass.DecryptText(context.Request.QueryString("album"))
Dim USerID As String = CommonClass.DecryptText(context.Request.QueryString("UserID"))
Dim galleryPath As String = ChasingCart.Common.ImagePathAlbumImagePhotoShare & USerID & "/" & AlbumNAme & "/"
If Not Directory.Exists(galleryPath) Then
End If
Dim xmlDoc As New System.Xml.XmlDocument()
Dim xmlnode As Xml.XmlNodeList
If File.Exists(galleryPath & "Descriptions.xml") Then
xmlDoc.Load(galleryPath & "Descriptions.xml")
End If
xmlnode = xmlDoc.SelectNodes("files/file")
Dim fileName As String = GetSafeFileName(galleryPath,files.FileName)
fileName = fileName.Replace(" ", "")
If Not Directory.Exists(galleryPath & "/Temp/") Then
Directory.CreateDirectory(galleryPath & "/Temp/")
End If
Dim TempxmlDoc As New System.Xml.XmlDocument()
If File.Exists(galleryPath & "/Temp/" & "Descriptions.xml") Then
TempxmlDoc.Load(galleryPath & "/Temp/" & "Descriptions.xml")
End If
Dim Tempxmlnode As Xml.XmlNodeList = TempxmlDoc.SelectNodes("files/file")
Dim str As Integer = 0
If File.Exists(galleryPath & "/Temp/" & "Descriptions.xml") Then
For Each objN As Xml.XmlNode In Tempxmlnode
If objN.Attributes("seqno").Value > str Then
str = objN.Attributes("seqno").Value
End If
For Each objN As Xml.XmlNode In xmlnode
If objN.Attributes("seqno").Value > str Then
str = objN.Attributes("seqno").Value
End If
End If
Dim xmlFile As System.Xml.XmlElement = TempxmlDoc.CreateElement("file")

xmlFile.SetAttribute("path", fileName)
xmlFile.SetAttribute("seqno", str + 1)
xmlFile.SetAttribute("mycomments", "")
xmlFile.SetAttribute("sno", str + 1)

TempxmlDoc.Save(galleryPath & "/Temp/" & "Descriptions.xml")
files.SaveAs(galleryPath & "/Temp/" & fileName)
'context.Response.ContentType = "text/plain"
'Dim serializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim result = files.FileName
context.Response.ContentType = "json"
context.Response.Write("[{""path"":""" & ChasingCart.Common.ImageUrlMemberImage & "getImage.aspx?t=bigthumbnail&u=" & CommonClass.EncryptText(USerID) & "&a=" & CommonClass.EncryptText(AlbumNAme) & "&f=" & fileName & """,""PhotoNo"":""" & str + 1 & """}]")


End If
End Sub
Private Function GetSafeFileName(ByVal path As String,ByVal fileName As String) As String
Dim newFileName As String = fileName.Replace(" ", "")
if newFileName.Length>40 Then
newFileName =newFileName.Substring(0,40)
End if
While (File.Exists(path & newFileName))
Dim RandNum As New System.Random()
Dim MyRandomNumber As Integer = RandNum.Next(100)
newFileName = MyRandomNumber & "_" & fileName
End While

Catch ex As Exception
End Try
Return newFileName
End Function
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Return False
End Get
End Property

End Class
Will Show on Your Page after That when you Click on Save button Than all Image Will Save
write Below code to Save Image in Your .vb File on Click Event of Save button

Protected Sub lnkUploadPhoto_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkUploadPhoto.Click
Dim galleryPath As String = ChasingCart.Common.ImagePathAlbumImagePhotoShare & CommonClass.getCustomerId & "/" & ViewState("AlbumName").ToString() & "/Temp/"
Dim galleryPathDest As String = ChasingCart.Common.ImagePathAlbumImagePhotoShare & CommonClass.getCustomerId & "/" & ViewState("AlbumName").ToString() & "/"
Dim xmlDoc As New Xml.XmlDocument
Dim xmlnode As Xml.XmlNodeList
Dim ds As New DataSet
Dim dt1 As New DataSet
If File.Exists(galleryPath & "/" & "Descriptions.xml") Then
xmlDoc.Load(galleryPath & "/" & "Descriptions.xml")
dt1.ReadXml(galleryPath & "/" & "Descriptions.xml")
End If
xmlnode = xmlDoc.SelectNodes("files/file")

Dim di As DirectoryInfo = New DirectoryInfo(galleryPathDest)
If Not di.Exists Then
End If
Dim descriptionsDest As New Xml.XmlDocument
If File.Exists(galleryPathDest & "/Descriptions.xml") Then
ds.ReadXml(galleryPathDest & "/Descriptions.xml")
End If
For Each FileName As String In Directory.GetFiles(galleryPath)
Dim index1 As Integer = FileName.LastIndexOf("/")
Dim name2 As String = FileName.Remove(0, index1 + 1)
If Not name2.Contains(".xml") Then
File.Copy(galleryPath & name2, galleryPathDest & name2, True)
File.Delete(galleryPath & name2)
End If
Dim dv As New DataView(dt1.Tables(0))
dv.Sort = "seqno"
Dim dt As DataTable = dv.ToTable
Dim node As Xml.XmlNode
If File.Exists(galleryPathDest & "Descriptions.xml") Then
descriptionsDest.Load(galleryPathDest & "Descriptions.xml")
node = descriptionsDest.SelectSingleNode("//files")
End If

For i As Integer = 0 To dt.Rows.Count - 1
Dim xmlFile As System.Xml.XmlElement = descriptionsDest.CreateElement("file")
Dim xmlnode1 As Xml.XmlNodeList = descriptionsDest.GetElementsByTagName("file")
xmlFile.SetAttribute("path", dt.Rows(i)(0).ToString())
xmlFile.SetAttribute("seqno", dt.Rows(i)(1).ToString())
xmlFile.SetAttribute("mycomments", dt.Rows(i)(2).ToString())
xmlFile.SetAttribute("sno", dt.Rows(i)(3).ToString())
descriptionsDest.Save(galleryPathDest & "Descriptions.xml")
descriptionsDest.Load(galleryPathDest & "Descriptions.xml")

objMgr.objErr.FunctionName.RemoveAt(objMgr.objErr.FunctionName.Count - 1)
Catch ex As Exception
'handle exceptions
objMgr.objErr.Exp = ex

End Try
End Sub


No comments:

Post a Comment