1)前台代码(Default.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UploadAttachment2._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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Label ID="lblOverWrite" runat="server" Text="覆盖现有文件"></asp:Label>
<asp:CheckBox ID="chkOverWrite" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="上传" οnclick="btnUpload_Click" />
<table>
<asp:Repeater ID="rptFiles" runat="server" onitemcommand="rptFiles_ItemCommand">
<HeaderTemplate>
<tr>
<td>编号</td>
<td>文件名</td>
<td>操作</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("Id") %></td>
<td><%#Eval("FileName") %></td>
<td>
<asp:LinkButton ID="lbtnDel" runat="server" CommandName="del" CommandArgument='<%#Eval("FileName") %>'>删除</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
</form>
</body>
</html>
2)后台代码
a)Default.aspx.cs
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.Configuration;
using Microsoft.SharePoint;
namespace UploadAttachment2
{
public partial class _Default : System.Web.UI.Page
{
string allowedExtensions = ConfigurationManager.AppSettings["allowedExtensions"];//允许的文件格式
private string webUrl = ConfigurationManager.AppSettings["webUrl"];//网站url
private string listName = ConfigurationManager.AppSettings["listName"];//列表名称
private string filePrefix = "AM_";//文件前缀
private int id = 1;
List<Attachment> attachments = new List<Attachment>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPostedAttachment();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (fileUpload.HasFile)//fileUpload包含文件
{
string filePath = fileUpload.FileName;
string fileExtension = Path.GetExtension(filePath);
if (IsAllowedExtension(fileExtension))//允许格式
{
long fileContentLenght = fileUpload.FileContent.Length;
if (IsAllowedContentLength(fileContentLenght))//文件2M以下
{
string fileName = filePrefix+Path.GetFileName(filePath);
byte[] fileBytes=fileUpload.FileBytes;
if (IsOverWrite())//覆盖文件
{
if (UploadAttachment(fileName, fileBytes, IsOverWrite()))
{
BindPostedAttachment();
Page.ClientScript.RegisterStartupScript(GetType(), "upload_success", "alert('上传文件成功!')", true);
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "upload_failure", "alert('上传文件失败!')", true);
}
}
else
{
if (!IsExistFile(fileName))//列表不存在fileName附件
{
if (UploadAttachment(fileName, fileBytes, IsOverWrite()))
{
BindPostedAttachment();
Page.ClientScript.RegisterStartupScript(GetType(), "upload_success", "alert('上传文件成功!')", true);
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "upload_failure", "alert('上传文件失败!')", true);
}
}
else//列表存在fileName附件
{
Page.ClientScript.RegisterStartupScript(GetType(), "file_is_exist", "alert('文件已经存在!')", true);
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "no_allowed_content_length", "alert('单个文件大小不能大于2M!')", true);
}
}
else//不允许格式
{
Page.ClientScript.RegisterStartupScript(GetType(), "no_allowed_extension", "alert('上传文件格式不正确!')", true);
}
}
else//fileUpload不包含文件
{
Page.ClientScript.RegisterStartupScript(GetType(), "has_no_file", "alert('请选择上传文件!')", true);
}
}
/// <summary>
/// 绑定上传的附件
/// </summary>
private void BindPostedAttachment()
{
GetPostedAttachments();
rptFiles.DataSource = attachments;
rptFiles.DataBind();
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileStream"></param>
/// <param name="overWrite"></param>
/// <returns></returns>
private bool UploadAttachment(string fileName, byte[] fileBytes, bool overWrite)
{
bool flag = false;
SPWeb web = null;
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
web = new SPSite(webUrl).OpenWeb();
});
web.AllowUnsafeUpdates = true;
SPList list = web.Lists[listName];
SPListItem item = list.GetItemById(id);
if (overWrite)//覆盖
{
try
{
item.Attachments.Recycle(fileName);
}
catch (Exception ex)
{ }
}
item.Attachments.Add(fileName, fileBytes);
try
{
item.Update();
flag = true;
}
catch (Exception ex)
{
flag = false;
}
finally {
web.Dispose();
}
return flag;
}
/// <summary>
/// 判断文件是否已经存在
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private bool IsExistFile(string fileName)
{
bool flag = false;
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPWeb web = new SPSite(webUrl).OpenWeb())
{
SPList list = web.Lists[listName];
SPListItem item = list.GetItemById(id);
for (int i = 0; i < item.Attachments.Count; i++)
{
if (item.Attachments[i] == fileName)
{
flag = true;
}
}
}
});
return flag;
}
/// <summary>
/// 获取所有上传的附件
/// </summary>
private void GetPostedAttachments()
{
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPWeb web = new SPSite(webUrl).OpenWeb())
{
SPList list = web.Lists[listName];
SPListItem item = list.GetItemById(id);
for (int i = 0; i < item.Attachments.Count; i++)
{
attachments.Add(new Attachment(i + 1, item.Attachments[i]));
}
}
});
}
/// <summary>
/// 上传文件是否是可以允许的格式
/// </summary>
/// <returns></returns>
private bool IsAllowedExtension(string fileExtension)
{
bool flag = false;
foreach (string allowedExtension in allowedExtensions.Split(';'))
{
if (fileExtension == allowedExtension)
{
flag = true;
break;
}
}
return flag;
}
/// <summary>
/// 上传文件大小是否允许
/// </summary>
/// <returns></returns>
private bool IsAllowedContentLength(long fileContentLenght)
{
bool flag = false;
if (fileContentLenght <= 2 * 1024 * 1024)
{
flag = true;
}
return flag;
}
/// <summary>
/// 判断是否覆盖
/// </summary>
/// <returns></returns>
private bool IsOverWrite()
{
bool flag = false;
if (chkOverWrite.Checked)
{
flag = true;
}
return flag;
}
/// <summary>
/// 删除附件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
protected void rptFiles_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "del")
{
string fileName=e.CommandArgument.ToString();
if (DelAttachment(fileName))
{
BindPostedAttachment();
Page.ClientScript.RegisterStartupScript(GetType(), "delete_success", "alert('删除文件成功!')", true);
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "delete_failure", "alert('删除文件失败!')", true);
}
}
}
/// <summary>
/// 删除附件
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public bool DelAttachment(string fileName)
{
bool flag = false;
SPWeb web = null;
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
web = new SPSite(webUrl).OpenWeb();
});
web.AllowUnsafeUpdates = true;
SPList list = web.Lists[listName];
SPListItem item = list.GetItemById(id);
item.Attachments.Recycle(fileName);
try
{
item.Update();
flag = true;
}
catch (Exception ex)
{
flag = false;
}
finally
{
web.Dispose();
}
return flag;
}
}
}
b)Attachment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UploadAttachment2
{
public class Attachment
{
public Attachment() { }
public Attachment(int id, string fileName)
{
this.Id = id;
this.FileName = fileName;
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string fileName;
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
}
}