*********************************************************************************
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Multiple file upload in asp.net using javascript</title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<p id="upload-area">
<input id="File1" type="file" runat="server" size="60" />
</p>
<p>
<a href="#" onclick="addTypeFile()">Attach another file</a>
</p>
<p><asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />
<script type="text/javascript">
function addTypeFile()
{
if (!document.getElementById || !document.createElement)
return false;
var uploadArea = document.getElementById ("upload-area");
if (!uploadArea)
return;
var newLine = document.createElement ("br");
uploadArea.appendChild (newLine);
var newTypeFile = document.createElement ("input");
newTypeFile.type = "file";
newTypeFile.size = "60";
if (!addTypeFile.lastAssignedId)
addTypeFile.lastAssignedId = 100;
newTypeFile.setAttribute ("id", "file1" + addTypeFile.lastAssignedId);
newTypeFile.setAttribute ("name", "file1:" + addTypeFile.lastAssignedId);
uploadArea.appendChild (newTypeFile);
addTypeFile.lastAssignedId++;
}
</script>
</form>
</body>
</html>
*********************************************************************************
using System;
using System.IO;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
private String path = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
path = Server.MapPath("~/Uploads/");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
String fileName = String.Empty;
String ContentType = String.Empty;
HttpFileCollection uploads = HttpContext.Current.Request.Files;
for (int i = 0; i < uploads.Count; i++)
{
//You can check Content Type also
//ContentType = uploads[i].ContentType;
//if (ContentType != "image/png" || ContentType != "image/jpeg")
//continue;
if (uploads[i].FileName.Length == 0)
continue;
// We don't need the path, just the name.
fileName = Path.GetFileName(uploads[i].FileName);
try
{
uploads[i].SaveAs(path + fileName);
Span1.InnerHtml = "Upload Successful.";
}
catch
{
Span1.InnerHtml = "Upload Failed.";
}
}
}
}
*********************************************************************************
Create a folder named Uploads in your solution
No comments:
Post a Comment