0

I have issue uploading image to list. In my .ascx file i declare html code like below

<label for="filetoupload">Picture upload</label>

<input  id="filetoupload" type="file" size="4" name="filetoupload"  />
<input id="browse-file-click" type="button" value="Click To Upload" />
<asp:Button runat="server" Text="Save" ID="btnSave" OnClick="btnSave_Click" />

In Javascript file i do below

 $("#filetoupload").on("change", function () {

    $("#file-name").html($(this).val().replace("C:\\fakepath\\", "")) 

}

in code behind under click event i do below

if (Page.Request.Form["filetoupload"] !=null)
{

string filename = Page.Request.Form["filetoupload"].ToString();

System.IO.File.OpenRead(filename);
System.Convert.ToInt32(fStream.Length));
 var webClient = new WebClient();
 byte[] imageBytes = webClient.DownloadData(filename);
 SPAttachmentCollection attachments = item.Attachments;
 attachments.Add(filename, imageBytes);
 item.Update();
 myList.Update();
 }

But when saving image i get exception as file not found. I am not able to get full file name and that is reason its throwing exception. How can i get rid of this issue. I dont want to use file upload control provided by .net. Is there any other way or how can i fix this issue?

**Update**

I add this code inside if(Page.Request)...

if (HttpContext.Current.Request.Files.Count > 0)
                            {
                                HttpFileCollection uploads = HttpContext.Current.Request.Files;
                                //SPAttachmentCollection attachments;

                                for (int i = 0; i < uploads.Count; i++)
                                {
                                    Stream fs = uploads[i].InputStream;
                                    byte[] fileContents = new byte[fs.Length];
                                    fs.Read(fileContents, 0, (int) fs.Length);
                                    fs.Close();
                                    //attachments = listItem.Attachments;
                                    string fileName = Path.GetFileName(uploads[i].FileName);
                                    //attachments.Add(fileName, fileContents);
                                }

                            }

But i get count as 0 from HttpContext.Current.Request.Files.Count

  • Why are you clearing path using Jquery? is there any specific reason? – Kalpesh Vaghela Jun 9 '15 at 8:51
  • So you would like to have the file as SharePoint list item attachment, or just as image in picture library? – Jussi Palo Jun 9 '15 at 8:53
  • @JussiPalo as an attachment in list – Happy Jun 9 '15 at 8:54
  • @KalpeshVaghela do you think that could be problem. Javascript code is something i have not written. got it from designer actually – Happy Jun 9 '15 at 8:56
  • @KalpeshVaghela if i dont clear then i get C:\fakepath\6.jpg.... so thats wrong – Happy Jun 9 '15 at 8:58
1

Below is your answer

Design mode code

<input type="file" runat="server" id="fuUploadFile" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /> 

Code behind

protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        SPWeb web = SPContext.Current.Web;
        SPList lst = web.Lists["SampleList"];
        SPListItem item = lst.Items.GetItemById(1);
        SPAttachmentCollection attachments = item.Attachments;
        attachments.Add(fuUploadFile.PostedFile.FileName, ReadStream(fuUploadFile.PostedFile.InputStream));
        item.Update();
    }
    public static byte[] ReadStream(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

Design of page

enter image description here

Hope it will helpful to you.

  • I told that i dont want to use file upload control – Happy Jun 9 '15 at 9:13
  • The main reason i dont want to use this control is because it comes with upload button and text box which i dont want – Happy Jun 9 '15 at 9:17
  • I have updated answer with html control – Kalpesh Vaghela Jun 9 '15 at 9:19
  • When i change it as per you said and click on button then i dont get dialogue to choose files. – Happy Jun 9 '15 at 9:29
  • You donot client onto directly "Upload" button. First click on file upload control and chose file. "Upload" button given in design in not upload button of file upload control instead it's "<asp:button" – Kalpesh Vaghela Jun 9 '15 at 9:31
1

The following might be the solution that you are looking for. But it is for attaching a document to a list item. But i still believe it can answer your question.

HTML

<input type="file" name="fileID_0" id="fileID_0" />

<asp:Button ID="btnSendRequest" CssClass="button" runat="server" Text="Send Request" OnClick="btnSendRequest_Click" />

C#

private void saveAttachment(SPWeb oSPWeb, SPListItem listItem)
            {

                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        oSPWeb.AllowUnsafeUpdates = true;

                        if (HttpContext.Current.Request.Files.Count > 0)
                        {
                            HttpFileCollection uploads = HttpContext.Current.Request.Files;
                            SPAttachmentCollection attachments;

                            for (int i = 0; i < uploads.Count; i++)
                            {
                                Stream fs = uploads[i].InputStream;
                                byte[] fileContents = new byte[fs.Length];
                                fs.Read(fileContents, 0, (int)fs.Length);
                                fs.Close();
                                attachments = listItem.Attachments;
                                string fileName = Path.GetFileName(uploads[i].FileName);
                                attachments.Add(fileName, fileContents);
                            }

                        }
                        listItem.Update();
                        //// Get the Attachment collection
                        //SPAttachmentCollection attachmentCollection = listItem.Attachments;

                        //Stream attachmentStream;
                        //Byte[] attachmentContent;

                        //// Get the file from the file upload control
                        //if (this.fulpAttachment.HasFile)
                        //{
                        //    attachmentStream = this.fulpAttachment.PostedFile.InputStream;

                        //    attachmentContent = new Byte[attachmentStream.Length];

                        //    attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);

                        //    attachmentStream.Close();
                        //    attachmentStream.Dispose();

                        //    // Add the file to the attachment collection
                        //    attachmentCollection.Add(this.fulpAttachment.FileName, attachmentContent);
                        //}

                        //// SPSecurity.CatchAccessDeniedException = false;

                        //// Update th list item
                        //listItem.Update();

                        oSPWeb.AllowUnsafeUpdates = false;
                    });
                }
                catch (Exception ex)
                {
                    lblMessage.Text = string.Format(Constants.Templates.WABErrorMessage_Markup, "New Site Request has been failed.");


                }


            }

Let me know if you have any questions

  • i get count 0 in HttpContext.Current.Request.Files.Count. Hence i dont get file name – Happy Jun 9 '15 at 9:59
  • Please help me. i am struggling – Happy Jun 9 '15 at 11:35
  • Please update the question with the current code that you are using. – Naveen Jun 9 '15 at 11:38
  • i updated. Please help – Happy Jun 9 '15 at 13:41
  • As per my understanding you don't need "Click To Upload" button and when you are clicking it before clicking btnSave, the file control is loosing its selection and that is the reason when you click on the actual button btnSave files count is showing 0. If my understanding is wrong please tell me what are you trying to do with "Click To Upload" button. – Naveen Jun 10 '15 at 11:24

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.