C# 前台:
先[写一个JS脚本:
<script type="text/javascript" language="Javascript">
function addFile()
{
var str = '<input type="file" size="30" name="File" runat ="server"><br>';
document.getElementById('myfile').insertAdjacentHTML("beforeend",str);
}
</script>
然后再加上:
<p id="myfile">
<INPUT type="file" size="30" NAME="File" runat ="server">
</p>
``````````````````````````````````
<input type="button" class="cbutton" value="新增附件(Add)" οnclick="addFile()" id="Button1">
<asp:Button ID="BT_Server" CssClass="cbutton" runat="server" OnClick="BT_Server_Click" />
后台上传按钮就写上:
protected void BT_Server_Click(object sender, EventArgs e)
{
string filepath = Server.MapPath("./") + "Document_file";
string UploadFileLastName = "";
string sUser_ProductsImageUrl = "";
HttpFileCollection myfiles = Request.Files;
for (int i = 0; i < myfiles.Count;i++)
{
HttpPostedFile userPostedFile = myfiles[i];//文件在本地的原始位置
try
{
if (userPostedFile.ContentLength > 0)
{
UploadFileLastName = userPostedFile.FileName.Substring(userPostedFile.FileName.LastIndexOf(".") + 1); //得到文件的扩展名
string NewUploadFileName = "";
//文件名称由
NewUploadFileName = "Document_" + "1110001111" + i.ToString() + "." + UploadFileLastName;//产生上传文件的名称
//imgsrc = NewUploadFileName;
string UserDirectory = "Document_file";//所要创建文件夹的名字
string UserPath = Server.MapPath("../" + UserDirectory).ToString();// + "//" + UserDirectory + "//" + "ProductsImages";
if (!System.IO.Directory.Exists(UserPath)) //如果文件夹不存在则创建
{
System.IO.Directory.CreateDirectory(UserPath);
}
userPostedFile.SaveAs(UserPath + "/" + NewUploadFileName);//用保存的方法将文件上载
sUser_ProductsImageUrl = "Document_file/" + NewUploadFileName;//得到服务端文件的虚拟路径
}
}
catch
{
JScript.Alert("上传失败!");
}
}
}
以上代码是本人原创,多有不足之处,请各位高手指教,谢谢!!!