2012-04-23 94 views
0

我正在为SharePoint Foundation Server 2010开发一个相当简单的可视WebPart。 它应该将图像文件上载到SharePoint服务器并在之后显示。 虽然我可以成功将文件上传到先前创建的文档库,但无法显示该文件(IE显示红色叉号)。当我使用SharePoint前端上传文件的确切副本时,可以打开它。我希望有人能告诉我我错过了什么。无法显示SharePoint中上传的图像文件

下面你可以找到成功文件上载到服务器的代码:

SPContext.Current.Web.AllowUnsafeUpdates = true; 
     string path = ""; 
     string[] fileName = filePath.PostedFile.FileName.Split('\\'); 
     int length = fileName.Length; 
     // get the name of file from path 
     string file = fileName[length - 1]; 
     SPWeb web = SPContext.Current.Web; 
     SPFolderCollection folders = web.Folders; 
     SPFolder folder; 
     SPListCollection lists = web.Lists; 
     SPDocumentLibrary library; 
     SPList list = null; 
     Guid guid = Guid.Empty; 

     if (lists.Cast<SPList>().Any(l => string.Equals(l.Title, "SPUserAccountDetails-UserImages"))) 
     { 
      list = lists["SPUserAccountDetails-UserImages"]; 
     } 
     else 
     { 
      guid = lists.Add("SPUserAccountDetails-UserImages", "Enthält Mitarbeiter-Fotos", SPListTemplateType.DocumentLibrary); 
      list = web.Lists[guid]; 
     } 

     library = (SPDocumentLibrary)list; 

     folder = library.RootFolder.SubFolders.Add("SPUserAccountDetails"); 

     SPFileCollection files = folder.Files; 
     Stream fStream = filePath.PostedFile.InputStream; 
     byte[] MyData = new byte[fStream.Length]; 
     Stream stream = new MemoryStream(); 
     stream.Read(MyData, 0, (int)fStream.Length); 
     fStream.Close(); 
     bool bolFileAdd = true; 
     for (int i = 0; i < files.Count; i++) 
     { 
      SPFile tempFile = files[i]; 
      if (tempFile.Name == file) 
      { 
       folder.Files.Delete(file); 
       bolFileAdd = true; 
       break; 
      } 
     } 
     if (bolFileAdd) 
     { 
      SPFile f = files.Add(file, MyData); 

      f.Item["ContentTypeId"] = "image/jpeg"; 
      f.Item["Title"] = file; 
      f.Item.SystemUpdate(); 

      SPContext.Current.Web.AllowUnsafeUpdates = false; 
      imgPhoto.ImageUrl = (string)f.Item[SPBuiltInFieldId.EncodedAbsUrl]; 
     } 

回答

0

没关系。我的代码似乎与文件内容混乱。我稍后会发布解决方案。

编辑: 我愚蠢和对不起: -/

我换成这样的:

Stream fStream = filePath.PostedFile.InputStream; 
byte[] MyData = new byte[fStream.Length]; 
Stream stream = new MemoryStream(); 
stream.Read(MyData, 0, (int)fStream.Length); 
fStream.Close(); 

与此:

Stream fStream = filePath.PostedFile.InputStream; 
byte[] MyData = new byte[fStream.Length]; 
BinaryReader binaryReader = new BinaryReader(fStream); 
MyData = binaryReader.ReadBytes((Int32)fStream.Length); 
fStream.Close(); 
binaryReader.Close(); 

,突然它的所有工作; - )