Search code examples
c#sharepointfile-uploadfieldtype

Sharepoint File FieldType


I am implementing a few SharePoint lists that require a file upload, putting the file in the list directory under a folder called /Lists/{ListName}/{RecordId}/filename.ext

How can I achive this using a fieldType, It get the FileUpload WebControl to render but am not receiving a file (FileUpload.HasFile always returns false) on Page Load checking for Page.IsPostBack?

public class UploadControl : BaseFieldControl {

    protected FileUpload fileupload;

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        //FIX FOR PROBLEM
        Page.Form.Enctype = "multipart/form-data";
        //FIX FOR PROBLEM

        if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New || PreviousControlMode == SPControlMode.Edit)
        {
            fileupload = new FileUpload();
            fileupload.ID = "fileUpload";
            Controls.Add(fileupload);
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (fileupload != null && Page.IsPostBack)
            throw new Exception("Uploaded Has File " + fileupload.HasFile);
            //Always Returns False
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        EnsureChildControls();
    }

    public override object Value
    {
        get
        {
            EnsureChildControls();
            if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
                return "FileName.EXT";
            return "";
        }
        set
        {
            EnsureChildControls();
            var str = (String)value;
        }
    }

}

Solution

  • I'm not completely sure on the code behind SharePoint page (don't have one handy), but be sure the form tag as has an:

    enctype='multipart/form-data'
    

    attribute as it is required for file uploads. If it's not, you could always do a

    Form.Enctype = "multipart/form-data"
    

    during an early page cycle method. Also, make sure the upload isn't happening asynchronously such as in an Update Panel as I don't believe it's allowed.