HTTP multipart/form-data in .NET

R

Robert DeFazio

I have a very specific need to send a file to a web server using VB.NET
2005 or 2008 on a desktop platform. I could do this readily in ASP.NET,
but my need is a bit more specific, and I don't know how to accomplish
it. Let me explain what I need to know how to do.

When I set up an ASP.NET page so that it sends a file, it uses the file
control and the form's content type is set to "multipart/form-data."
When the submit button is clicked, ASP.NET handles the streaming of the
data to the receiving server automatically by spooling it out as fast as
the receiving server can accept it.

What I want to do is to regulate the streaming process so that I can (a)
set the size of the chunks of data being sent, (b)control the number of
chunks of data that are sent at any given point in time, and (c)be able
to pause the process at my discretion.

The metalogic of the process would be something like this:

1. Create the message header(s) that must appear at the outset of the
transmission.
2. Estgablish the size of the chunks of data to be sent.
3. Start sending the message.
4. When the time comes for the chunks of the file to be streamed,
prepare each chunk and send it.
5. Allow for some client-side capability to pause the transmission
process.
6. Complete the transmission.
7. Receive back any confirming message and parse it to determine if the
file was received correctly.

I am not looking for a complete solution, but rather some code that
identifies all the moving parts and shows sample code that illustrates
how to connect them. With that in hand, I believe that I can then
produce a working solution that will give me the ability to govern the
rate of the data being streamed to the recipient server and the ability
to pause the process at my discretion.

Any help will be greatly appreciated.
 
M

Michel Posseth [MCP]

I have showed the multi part form thingy from a client a few weeks ago in
this group ( for someone who wanted to send pictures to twitter )
dig , dig , dig , no , no ,no oh, hmmmm , yes here it is ! you might be
able to convert it to your needs

#############
<CLASS CODE >


'Michel Posseth [MCP]
'Created : 23-02-2009
'(e-mail address removed)
Imports System
Imports System.IO
Imports System.Net
Imports System.Xml
Imports System.Web
Imports System.Collections.Generic
Imports System.Text
Namespace VBDC
Public Class ClsTwitPic
Public Function SendPicToTwitPic(ByVal userName As String, ByVal
password As String, ByVal Message As String, ByVal ImgPath As String) As
String
Using fs As System.IO.FileStream = New FileStream(ImgPath,
FileMode.Open, FileAccess.Read)
Dim ImgData As Byte() = New Byte(fs.Length - 1) {}
fs.Read(ImgData, 0, ImgData.Length)
Return SendPicToTwitPic(userName, password, ImgData,
Message)
End Using
End Function
Private Function SendPicToTwitPic(ByVal UserName As String, ByVal
PassWord As String, ByVal Image As Byte(), Optional ByVal Message As String
= "", Optional ByVal Uri As String = "http://twitpic.com/api/uploadAndPost")
As String
Dim ret As String = String.Empty
Dim request As HttpWebRequest =
DirectCast(WebRequest.Create(Uri), HttpWebRequest)
request.Method = "POST"
request.Timeout = 30000


If Not String.IsNullOrEmpty(UserName) AndAlso Not
String.IsNullOrEmpty(PassWord) Then


Dim boundary As String = System.Guid.NewGuid().ToString()


request.Credentials = New NetworkCredential(UserName,
PassWord)


request.Headers.Add("Accept-Language",
"vb,en-us;q=0.7,en;q=0.3")
request.PreAuthenticate = True
request.ContentType =
String.Format("multipart/form-data;boundary={0}", boundary)


Dim header As String = String.Format("--{0}", boundary)
Dim footer As String = header & "--"


Dim contents As New StringBuilder()


contents.Append(header)
contents.Append(vbCrLf)
contents.Append("Content-Disposition:
form-data;name=""username""" & vbCrLf)
contents.Append(vbCrLf)
contents.Append(UserName)
contents.Append(vbCrLf)


contents.Append(header)
contents.Append(vbCrLf)
contents.Append("Content-Disposition:
form-data;name=""password""" & vbCrLf)
contents.Append(vbCrLf)
contents.Append(PassWord)
contents.Append(vbCrLf)


If Not String.IsNullOrEmpty(Message) Then
contents.Append(header)
contents.Append(vbCrLf)
contents.Append("Content-Disposition:
form-data;name=""message""" & vbCrLf)
contents.Append(vbCrLf)
contents.Append(Message)
contents.Append(vbCrLf)
End If


contents.Append(header)
contents.Append(vbCrLf)
contents.Append("Content-Disposition:form-data;
name=""media"";filename=""image.jpg""" & vbCrLf)
contents.Append("Content-Type: image/jpeg" & vbCrLf)
contents.Append(vbCrLf)


Dim Einde As String = vbCrLf & header & vbCrLf
Dim BodyBytes As Byte() =
Encoding.UTF8.GetBytes(contents.ToString())
Dim footerBytes As Byte() = Encoding.UTF8.GetBytes(Einde)


request.ContentLength = BodyBytes.Length + Image.Length +
footerBytes.Length


Using requestStream As Stream = request.GetRequestStream()
requestStream.Write(BodyBytes, 0, BodyBytes.Length)
requestStream.Write(Image, 0, Image.Length)
requestStream.Write(footerBytes, 0, footerBytes.Length)
requestStream.Flush()
requestStream.Close()
Using response As WebResponse = request.GetResponse()
Using reader As New
StreamReader(response.GetResponseStream())
ret = reader.ReadToEnd()
End Using
End Using
End Using
End If


Return ret
End Function


End Class


End Namespace


</CLASS CODE>


Usage


Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click


Dim TwitPic As New VBDC.ClsTwitPic


Debug.WriteLine(TwitPic.SendPicToTwitPic("YourUsername",
"YourPassword", "some text ", "C:\FullPathToPic.jpg"))


End Sub


End Class


the response i got was


<?xml version="1.0" encoding="UTF-8"?>
<rsp status="ok">
<statusid>1242482808</statusid>
<userid>21698827</userid>
<mediaid>1nmne</mediaid>
<mediaurl>http://twitpic.com/1nmne</mediaurl>
</rsp>


when viewing my twitter account ( michel1973 ) i found my send picture
and the text i entered so it works


Regards


Michel Posseth [MCP] , VBDC
http://www.vbdotnetcoder.com/
######################################

HTH



Michel Posseth
 
C

Cor Ligthert

Be aware that you cannot send without special features controled by the user
(or his systemadministrator) from a webpage data to client using Net. You
need for that an activeX (seldom accepted by the user).

(If you can there is in about 2 weeks a security update to prevent that)

Cor
 
M

Michel Posseth

I can :)


The TS stated that he has a client program that connects to the web
As soon as the user has internet acces and can reach a website / webservice
i can send anything i want to the client


By the way i did this alredy in 2001 with VB 6 and classic ASP and that
program is used until the day of today by a Polish customer from my past
employer
it serilaizes a ACCESS 2000 reporting database generated in Schiedam
Netherlands to the desktop of a salesman in Katowice Poland :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top