Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

Upload Multiple Files Using WebClient.UploadFile Method

In this post I will demonstrate how to use WebClient.UploadFile to upload multiple files to the server. The attachment procedure is like gmail which allows you to select one file after the other.

 

<a href="#" onclick="attachFile()">Attach a file</a>

<script language="javascript" type="text/javascript">

var selectedFiles = '';

 

function ReceiveServerData(response)

{

alert(response);

}

function uploadFile()

{

var fileList = document.getElementById("fileDivBox").getElementsByTagName("INPUT");

 

for(i=0; i<fileList.length;i++)

{

selectedFiles += fileList[i].value + "|";

}

 

CallServer(selectedFiles,'');

}

function attachFile()

{

var fu = document.createElement("INPUT");

fu.type = "file";

 

 

var br = document.createElement("<BR>");

 

document.getElementById("fileDivBox").appendChild(fu);

document.getElementById("fileDivBox").appendChild(br);

}

</script>

The attachFile function creates a new input element of type "file" and appends it to the DIV element. When the user clicks the upload button the uploadFile function is fired which iterates through the DIV (fileDivBox) element and gets all the selected files and sends them to the server.

The ASP.NET page uses client callbacks. If you are interested to learn about client callbacks then visit this link.

 

public void RaiseCallbackEvent(string eventArgument)

{

string[] files = (eventArgument.TrimEnd('|')).Split('|');

WebClient client = new WebClient();

foreach (string file in files)

{

client.UploadFile("http://localhost:1566/FileServer.aspx", "POST", file);

}

}

The RaiseCallbackEvent is where the upload takes place. I am using WebClient class UploadFile method to upload the file. The file is posted to the FileServer.aspx page where I can retrieve it and save it in the server's folder.

FileServer.aspx:

protected void Page_Load(object sender, EventArgs e)

{

string path = @"C:\UploadedFiles\"; // server folder

string[] keys = Request.Files.AllKeys;

foreach(String key in keys)

{

HttpPostedFile file = Request.Files[key];

file.SaveAs(path + file.FileName);

}

 

}

I will be writing an article about this technique so stay tunned on GridViewGuy.

Sponsor

Published Thursday, October 25, 2007 11:34 AM by azamsharp

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below