Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

WebClient.UploadFile vs old html postmethod

Status
Not open for further replies.

tyreejp

Programmer
Apr 20, 2005
114
US
I have two web pages. Page A has an old school form to post a file to another page. Code:

<form id="form1" action="WebForm1.aspx" method="post">
<input type="file" id="Upload" />
<input type="submit" id="submit" value="send" />
</form>

Problem is, the receiving side's code behind doesn't ever see that a file was posted. Code:

For Each f In Request.Files.AllKeys
<Do something with f>
Next f

However, if I change things on the first page and use the WebClient.UploadFile method, the receiving page does seethe file in its collection.

Does anyone know why?!?

James

--
James
 
there is a special header tag that tells the page your uploading a file. the file upload control prepopulates this header. if your form doesn't include the header, then it never knows a file is being uploaded.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
I've never heard of that before. Could you provide an example?

--
James
 
sorry not a header, but a form attribute [tt]enctype="multipart/form-data"[/tt].
Code:
<form enctype="multipart/form-data">
   <input type="file" />
</form>
or
Code:
<form>
   <asp:FileUpload />
</form>


Jason Meckley
Programmer
Specialty Bakers, Inc.
 
I hate to be a pest... :(

I changed it to the following and still in the other page (two seperate .aspx pages) Request.Files is empty. Any other suggestions?? I'm getting desperate! :)
Code:
<form id="form1" action="WebForm1.aspx" method="post" enctype="multipart/form-data">
    <input type="file" id="Upload" />
    <input type="submit" id="submit" value="send" />       
</form>

--
James
 
why are you using the html? since your posting to an aspx file use the server control?

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
My goal is to have a web page on the front end waiting for our customer to post a file to it. That page will take tthe posted file which is xml and call a web service on a middle tier server passing it the xml. The WebControl.UploadFile method I was using was to just test it all. Our customer won't be able to use that method. They will do a simple html post. I have no control over what they use to post the file.

--
James
 
why not have the client call the web service directly?

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
security reasons". None of our web services are exposed to customers.

--
James
 
since your working directly with html try forum215. they may be able to provide more insight.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
just saw thread215-1419185. and they sent you back here :)

ok thinking about this more. the problem is your trying to mix client side controls with server side code. you'll need to pick one (either html or asp.net). now that said this trick might work.
Code:
<form id="form1" action="WebForm1.aspx" method="post" enctype="multipart/form-data">
    <input type="file" id="Upload" [COLOR=blue]runat="server"[/color] />
    <input type="submit" id="submit" value="send" />       
</form>

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
I laughed at that too. :)

What you just said makes a lot of sense. I'm home now but will mock up something here and see if it works and let you know!

--
James
 
Hi,

I have been dealing with more or less the same problem. I want to post a multipart form to an external webservice (actually a php page) on an ASP.NET page. The annoying thing is, that when you do this with simple HTML it is bloody simple, because the browser takes care of the rest. On an ASP.NET page, however, I found that the problem is that the webform always has to post back to itself in order to make the web controls work. So you cannot really make it post to another webpage.

After some googling I pieced together a complex solution using HttpWebRequest that I pasted below. It actually works except for one thing: As far as I can tell, the uploaded file included in the form probably is not arriving in a state that can be used/processed/recognized by the receiving end. Can anyone go through my code and tell me where it may go wrong. If you don't see anything wrong please let me know too, because then the fault may lie on the receiving end.

Code:
if (fupChooseClip.HasFile)
        {
            upload = (HttpWebRequest)WebRequest.Create(strUploadUrl);
            upload.Method = "POST";
            upload.ContentType = "multipart/form-data; boundary=" + boundary;
            upload.Timeout = 60000;

            postString += appendMultiPartFormField("sid", sid, boundary);
            postString += appendMultiPartFormField("tid", tid.ToString(), boundary);
            postString += appendMultiPartFormField("user", userid.ToString(), boundary);
            postString += appendMultiPartFormField("titel", txtClipTitle.Text, boundary);
            postString += appendMultiPartFormField("info", txtClipDescription.Text, boundary);
            postString += appendMultiPartFormField("musik", "0", boundary);
            postString += appendMultiPartFormFile("filedata", fupChooseClip.FileName, boundary);

            byte[] formBytes = Encoding.UTF8.GetBytes(postString);
            byte[] fileBytes = fupChooseClip.FileBytes;
            byte[] trailBytes = Encoding.UTF8.GetBytes(boundary);

            upload.ContentLength = formBytes.Length + fileBytes.Length + trailBytes.Length;

            requestStream = upload.GetRequestStream();
            requestStream.Write(formBytes, 0, formBytes.Length);
            requestStream.Write(fileBytes, 0, fileBytes.Length);
            requestStream.Write(trailBytes, 0, trailBytes.Length);

            try
            {
                httpWebResponse = (HttpWebResponse)upload.GetResponse();
                responseStream = httpWebResponse.GetResponseStream();
            }
            catch (WebException wex)
            {
                if (wex.Status == WebExceptionStatus.Timeout)
                    lblDebug.Text = "Timeout!";
                else
                    lblDebug.Text = "fejl: " + wex.Message;
            }
            
            requestStream.Close();

  

    private String appendMultiPartFormField(String fieldName, String fieldData, String boundary)
    {
        String strReturn = "";

        strReturn += "--" + boundary + "\r\n";
        strReturn += "Content-Disposition: form-data; name=\"" + fieldName + "\"" + "\r\n";
        strReturn += "\r\n";
        strReturn += fieldData + "\r\n";

        return strReturn;
    }

    private String appendMultiPartFormFile(String fieldName, String fileName, String boundary)
    {
        String strReturn = "";

        strReturn += "--" + boundary + "\r\n";
        strReturn += "Content-Disposition: form-data; name=\"" + fieldName + "\"; ";
        strReturn += "filename=\"" + fileName + "\"; ";
        strReturn += "Content-Type: application/octet-stream" + "\r\n";
        strReturn += "\r\n";

        return strReturn;
    }

    private String makeBoundary()
    {
        String tmp = "--------";
        Random randNum = new Random();

        char[] characterArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

        for (int i = 0; i < 8; i++)
        {
            tmp += characterArray[(int)((characterArray.GetUpperBound(0) + 1) * randNum.NextDouble())];
        }

        return tmp;
    }


Fedor Steeman
Geological Museum Copenhagen
Denmark
 
So you cannot really make it post to another webpage.

Have you looked to see if you are using a control with a PostBackUrl property? Several of the server controls have this....
 
Interesting point, but none of the enclosing server webcontrols have this property:

Code:
<asp:Panel ID="pnlUploadClip" runat="server" CssClass="ntv-klipform">
    <div>
        <label for="fupChooseClip">Url til klip</label>
        <asp:FileUpload ID="fupChooseClip" runat="server">							            
        </asp:FileUpload>
    </div>
    <div>
        <label for="txtClipTitle">Titel</label>
        <asp:TextBox ID="txtClipTitle" runat="server"/>
    </div>
    <div>
        <label for="txtClipTags">Tags</label>
        <asp:TextBox ID="txtClipTags" runat="server"/>    
    </div>
    <div>
        <label for="txtClipDescription">Beskrivelse</label>
        <asp:TextBox ID="txtClipDescription" runat="server" Height="80px" TextMode="MultiLine"></asp:TextBox>
    </div>
    <div class="ntv-kat">
        <label for="ddlXstreamCategories">Kategori</label>
        <asp:DropDownList ID="ddlXstreamCategories" runat="server"></asp:DropDownList>
    </div>
    <div class="ntv-klipform2">
        <div class="ntv-tip">
	        <label for="txtEmailTip"><strong>Tip en el. flere om klippet</strong><br/>
	        (Adskil e-mail adresser med komma)</label>
	        <br/>
	        <br/>
	        <asp:TextBox ID="txtEmailTip" runat="server" CssClass="ntvcommon"/>
        </div>
        <div>
            <asp:CheckBox ID="chkClip" runat="server" CssClass="checkboxklip" />
	        <label for="chkClip">Ja, jeg er indforst&aring;et med <a href="#">Ekstra Bladets regler</a><br/>
	        for upload af videoklip p&aring; nationen!tv</label>
        </div>
        <div class="ntv-sklip">
	        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="fupChooseClip"
                ErrorMessage="vldClipSelectedValidator">Du har glemt at vælge en fil!</asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="vldFiletypeValidator" runat="server" ControlToValidate="fupChooseClip"
                ErrorMessage="Du kan kun uploade videokllip af følgende formater: avi, mpeg, quicktime, wmv, swf)"
                ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.avi|.mpeg|.mpg|.mp4|.mov|.qt|.wmv|.swf|.flv)$"
                Width="317px"/>
            <asp:Button ID="btnUploadClip" runat="server" CssClass="ntv-submit2" Text="OK" Width="91px" OnClick="btnUploadClip_Click" />
        </div>
    </div>
</asp:Panel>

Fedor Steeman
Virksomheds-IT http://www.virksomheds-it.dk/
Denmark
 
An ASP:Button most certainly has a PostBackURL property.
 
Good point! So I understand that I can make the form being posted to another URL by setting the PostBackUrl of an enclosed server control, most obviously <asp:Button ID="btnUploadClip"...

But won't this post the entire asp_net form with all its postback information to the other url? How can I make it postback only the field values that are relevant, i.e. the ones in the panel? Can I just nest another form inside it?

And how will this affect browsing? Won't the browser be redirected to the particular URL? The way it is implemented now, the browser stays on the page, while another http-POST is sent to the eksternal URL.



Fedor Steeman
Virksomheds-IT http://www.virksomheds-it.dk/
Denmark
 
Can I just nest another form inside it?

You can only have one form tag on a page.

It appears that you need some partial rendering. Have you considered using AJAX?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top