SharePoint 上传附件二

上一篇(SharePoint 上传附件)文章最后遇到的问题是为什么可以通过控件的FileBytes来获取文件流,而自己通过byte[]和Stream从PostedFile中却无法获得文件字节。

查过一些文档后发现有可能是这几种原因造成的:

1、 页面 form 参数enctype 设置不对. 要加入enctype= "multipart/form-data ";

2、input type=file 至少有一个是需要添加 runat="server",这样后台才能拿到数据

3、form中可能用了Ajax;

对于第2、3、条原因已经排除,第1条在Sharepoint页面中(指定了Master页)也不方便更改,值得怀疑的是,我在普通的ASPX页面中也没有做任何设置,就可以通过Stream获取PostedFile的字节;

不过偶然发现Sharepoint下面却可以通过SaveAs的方法来将上传文件保存到服务器的文件系统,而不是数据库。

实现多文件上传,先将欲上传文件通过Request.Files[index].SaveAs方法保存到wpresources文件夹下的一个目录中,而后通过Stream获取这些文件的字节保存至SPListItem的Attachments属性下,最后再删除这个临时文件夹:

ContractedBlock.gif ExpandedBlockStart.gif Code
string serverPath = Server.MapPath(@"\wpresources");
            
string myDir = DateTime.Now.ToString().Replace(':''_');

            
for (int index = 0; index < Request.Files.Count; index++)
            {
                
if (Request.Files[index].ContentLength > 0)
                {
                    
if (!System.IO.Directory.Exists(serverPath + @"\" + myDir))
                    {
                        System.IO.Directory.CreateDirectory(serverPath 
+ @"\" + myDir);
                    }

                    
string filename = System.IO.Path.GetFileName(Request.Files[index].FileName);
                    Request.Files[index].SaveAs(serverPath 
+ @"\" + myDir + @"\" + filename);
                }
            }

            
if (System.IO.Directory.Exists(serverPath + @"\" + myDir))
            {
                
string[] files = System.IO.Directory.GetFiles(serverPath + @"\" + myDir);
                
foreach (string file in files)
                {
                    System.IO.FileStream fStream 
= new FileStream(file, FileMode.Open);
                    
byte[] contents = new byte[fStream.Length];
                    fStream.Read(contents, 
0, contents.Length);
                    fStream.Close();
                    fStream.Dispose();
                    _iptService.AddAttachments(queryItemId, webRUrl, contents, System.IO.Path.GetFileName(file));
                }
            }

            
if (System.IO.Directory.Exists(serverPath + @"\" + myDir))
            {
                System.IO.Directory.Delete(serverPath 
+ @"\" + myDir, true);
            }

转载于:https://www.cnblogs.com/jerryshi/archive/2009/04/08/1431544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值