0

我正在为 SharePoint Foundation Server 2010 开发一个相当简单的可视化 WebPart。它应该将图像文件上传到 SharePoint 服务器并在之后显示它。虽然我可以成功地将文件上传到以前创建的文档库,但无法显示文件(IE 显示红色叉号)。当我使用 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];
        }
4

1 回答 1

0

Never mind. My code seems to mess with the file content. I'll post the solution later.

edit: I'm stupid and sorry :-/

I replaced this:

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

with this:

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();

and suddenly it all worked ;-)

于 2012-04-23T14:03:04.313 回答