2

我有一个包装在 SharePoint 2007 网站中的 ASP.NET 应用程序。在这个应用程序中,我允许用户创建请求,他们还可以为请求上传支持文件。当用户上传 .docx 或 .xlsx 类型的支持文档(迄今为止我发现它们已损坏的唯一两个)时,它们正在“损坏”,从某种意义上说,当我尝试打开它们时,我会收到一个提示留言说:

“Excel 在 'Book1.xlsx' 中发现不可读的内容。是否要恢复此工作簿的内容?如果您信任此工作簿的来源,请单击是”

当我单击是时,它会修复文件并正确显示内容,但这对用户来说是不可接受的。我什至不希望他们有问题。

这是我的上传点击事件的代码(VB.NET):

Private Sub Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
    Dim currentUser As SPUser = SPContext.Current.Web.AllUsers("SHAREPOINT\SYSTEM")
    Dim currentUserToken As SPUserToken = currentUser.UserToken
    Using currentSite As SPSite = New SPSite(SPContext.Current.Web.Url, currentUserToken)

        Using CurrentWeb As SPWeb = currentSite.OpenWeb
            CurrentWeb.AllowUnsafeUpdates = True

            Dim attachmentList As SPList = CurrentWeb.Lists("Requests")

            Dim item As SPListItem = attachmentList.GetItemById(CurrentRequestId)

            If FileUpload.PostedFile.ContentLength > Nothing And FileUpload.HasFile Then
                Dim fStream As Stream = FileUpload.PostedFile.InputStream
                Dim contents() As Byte = New Byte(fStream.Length) {}

                fStream.Read(contents, 0, CType(fStream.Length, Integer))
                fStream.Close()
                fStream.Dispose()

                Dim attachments As SPAttachmentCollection = item.Attachments
                Dim fileName As String = Path.GetFileName(FileUpload.PostedFile.FileName)
                attachments.Add(fileName, contents)
                item.Update()
            Else
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "disp_msg", "<script type='text/javascript'>alert('The file contains 0 Bytes of data and will be deleted.'); </script>")
            End If
        End Using
    End Using
    DisplayAttachment(CurrentRequestId)
    btnSave.Focus()
Catch ex As Exception
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "disp_msg", "<script type='text/javascript'>alert('Error Uploading File: " & ex.Message & "'); </script>")
End Try
End Sub

任何帮助,将不胜感激。提前致谢。

4

1 回答 1

4

您遇到的问题在这一行:

Dim contents() As Byte = New Byte(fStream.Length) {}

它应该是

Dim contents() As Byte = New Byte(fStream.Length - 1) {}

VB.NET 数组指定了上限 - 而不是长度 - 由于 VB.NET 是从零开始的 - 旧行在末尾创建了一个额外的字节。

这通常不是问题,但 docx 和 xlsx 文件对这个额外的字节更敏感。

于 2013-03-05T15:10:04.583 回答