1

I am trying to upload a pdf file to a Document set using following code, but it generates this error File contains corrupted data. when it comes to the last line of the code

ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("PlaceHolderMain");
FileUpload fileUpload = (FileUpload)cph.FindControl("AddPdfFileUpload");

if (fileUpload.HasFile)
{
    DocumentSet documentSet = DocumentSet.GetDocumentSet(ListItem.Folder);

    byte[] pdfBytes = fileUpload.FileBytes;


    SPContentTypeId contentTypeId = List.ContentTypes["TemplateCT"].Id;

    string documentSetName = ListItem.Name;
    SPFolder targetFolder = List.RootFolder;
    Hashtable properties = ListItem.Properties;
    DocumentSet newDocSet = DocumentSet.Import(pdfBytes, documentSetName, targetFolder, contentTypeId, properties, CurrentWeb.CurrentUser);

}

I need to retrieve the FileUpload using above code because it has been added programmatically. I have debugged the code and the pdfBytes contains data and isn't empty.

1

When uploading to SharePoint I would suggest doing it like this instead.

FileStream fileStream = File.OpenRead(documentPath);
SPFile file = documentLibrary.Files.Add(destinationSiteUrl + "/" + documentName, fileStream);
documentLibrary.Update();

Note that the Add method has more input parameters (Override methods). But works great for all types of files if you use a FileStream.

SPFile file is there if you want to get the ListItem later to add metadata... use the id (file.Item.ID)

Also worth mentioning is that you have to update the library to complete the upload.

Edit: Upload to SharePoint Document set.

  • Get the SPFolder from the document set.
  • Use a file stream or byte array etc. to hold the information of the document.
  • Then use the destination with filename(with extention (.pdf))

Code:

byte[] pdfBytes = fileUpload.FileBytes; 
SPFolder dsFolder = documentSet.Folder; 
dsFolder.Files.Add(dsFolder.Url + "/" + fileName, pdfBytes); 
  • 1
    Thanks I have solved the problem but not using this metod. this is the solution byte[] pdfBytes = fileUpload.FileBytes; SPFolder dsFolder = documentSet.Folder; dsFolder.Files.Add(dsFolder.Url + "/" + fileName, pdfBytes); – Medes Dec 17 '14 at 10:24
  • You used dsFiles.Files.Add so you used the method i answered with ;) – George Norberg Dec 22 '14 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.