先看效果图
webpart:
文档库:
成功上传结果:
查看文档库:
代码部分
前台:
<div id="Upload"> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="上载到文档库" onclick="Button1_Click" /> <br /> <asp:Panel ID="Panel1" runat="server"></asp:Panel> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </div>
Button1_Click事件:
protected void Button1_Click(object sender, EventArgs e) { this.UploadFileToDocLib(SPContext.Current.Web, "456", this.FileUpload1, 1); }
UploadFileToDocLib的方法:
public void UploadFileToDocLib(SPWeb web, string docLibName, FileUpload fUpload, int itemId) { string FileName = FileUpload1.PostedFile.FileName; if (FileName == "") { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), string.Format("<script>alert('上传文件不能为空!')</script>")); } else { SPList list = web.Lists.TryGetList(docLibName); SPDocumentLibrary docLib = (SPDocumentLibrary)list; if (fUpload.HasFile) { string file_type = FileUpload1.PostedFile.ContentType; string file_KB = FileUpload1.PostedFile.ContentLength.ToString() + "KB<br>"; string fn = System.IO.Path.GetFileName(fUpload.PostedFile.FileName); System.IO.Stream stm = fUpload.PostedFile.InputStream; int iLength = (int)stm.Length; if (iLength > 0) { SPFolder rootFolder = docLib.RootFolder; Byte[] filecontent = new byte[iLength]; stm.Read(filecontent, 0, iLength); try { SPFile f = rootFolder.Files.Add(fn, filecontent); SPListItem item = f.Item; item["ItemID"] = itemId; item.SystemUpdate(); stm.Close(); Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), string.Format("<script>alert('成功上传!')</script>")); string URL = "http://amid01110/456/" + FileName + " "; ////循环添加label for (int i = 0; i < 1; i++) { Label l = new Label(); l.ID = "lbl" + i; l.Text = "</br>" + "<a href='" + URL + "' target='_blank' >" + fn + "</a>" + "大小" + file_KB + "上传文件成功";//label属性texbox的值 Panel1.Controls.Add(l); } } catch (Exception) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), string.Format("<script>alert('文件名存在!')</script>")); } } }