1) 前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="VSFileUpLoad._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 runat="server">
<title></title>
<script language ="javascript" type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script language="javascript" type="text/javascript">
function isCoverFile() {
if (confirm("文件存在,是否覆盖?")) {
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json",
url: "Default.aspx/Cover",
dataType: 'json',
success: function(result) {//回调函数,result,返回值
if (result.d == true) {
alert("覆盖成功!");
}
else {
alert("覆盖失败!");
}
}
});
}
}
function uploadSuccess(){//上传成功
alert("上传成功!");
}
function uploadError() {//上传失败
alert("上传失败!");
}
function fileIsNull(){//上传文件为空
alert("请选择上传文件!");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="ContentPanel" runat="server"></asp:Panel>
<asp:Button ID="btnFileUpload" runat="server" Text="提交"
οnclick="btnFileUpload_Click" />
</div>
</form>
</body>
</html>
2) 后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;
namespace VSFileUpLoad
{
public partial class _Default : System.Web.UI.Page
{
private static FileUpload FileUpload2;
private static string filePath="";
protected void Page_Load(object sender, EventArgs e)
{
FileUpload2 = new FileUpload();
FileUpload2.ID = "FileUpload2";
this.FindControl("ContentPanel").Controls.Add(FileUpload2);
}
protected void btnFileUpload_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)//上传文件存在
{
string savePath = Server.MapPath(@"~/pic");//文件夹路径
if (!Directory.Exists(savePath))//文件夹不存在
{
Directory.CreateDirectory(savePath);//创建文件夹
}
string fileName = FileUpload2.FileName;//文件名字
filePath = savePath + @"/" + fileName;//文件路径
if (File.Exists(filePath))//文件存在
{
Page.ClientScript.RegisterStartupScript(GetType(), "fileExist", "isCoverFile();", true);
}
else//文件不存在
{
try
{
FileUpload2.SaveAs(filePath);//添加文件
Page.ClientScript.RegisterStartupScript(GetType(), "uploadSuccess", "uploadSuccess();", true);
}
catch(Exception ex)
{
Page.ClientScript.RegisterStartupScript(GetType(), "uploadError", "uploadError();", true);
}
}
}
else //不存在上传文件
{
Page.ClientScript.RegisterStartupScript(GetType(), "fileIsNull", "fileIsNull();", true);
}
}
/// <summary>
/// 覆盖文件
/// </summary>
/// <param name="allPath"></param>
/// <returns></returns>
[WebMethod]
public static bool Cover()
{
bool flag = false;
try
{
FileUpload2.SaveAs(filePath);//添加文件
flag = true;
}
catch (Exception ex)
{
flag = false;
}
return flag;
}
}
}