Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I am facing critical problem that How to make webservice that uses TransferFile() method by multipart form data?.
I have write following code for it:
C#
[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void TransferFile()
        {

            HttpContext postedContext = HttpContext.Current;
            HttpFileCollection Request = postedContext.Request.Files;
            foreach (HttpPostedFile item in Request)
            {
                string filename = item.FileName;

                byte[] fileBytes = new byte[item.ContentLength];
                item.InputStream.Read(fileBytes, 0, item.ContentLength);
                TransferFile(filename, fileBytes);

                //objFileTransfer.TransferFile(filename, fileBytes);
                retJSON = js.Serialize(new { Result = objFileTransfer.TransferFile(filename, fileBytes) });
                Context.Response.Write(retJSON);
                // fileBytes now contains the content of the file
                // filename contains the name of the file
            }            
        }

Is this webservice get multipart form data?
When an iPhone developer consume this api they are not getting response.


C#
private FtpWebRequest ftpRequest = null;
        //private FtpWebResponse ftpResponse = null;
        private Stream ftpStream = null;
        private int bufferSize = 2048;

        public string TransferFile(string filename, byte[] fileContent)
        {
            string strMsg = string.Empty;
            try
            {
                
                /* Create an FTP Request */
                String uploadUrl = String.Format("{0}/{1}/{2}", "ftp://Address", "DirectoryName", filename);
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential("Username", "Password");
                /* When in doubt, use these options */
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                try
                {
                    
                    ftpRequest.ContentLength = fileContent.Length;

                    Stream requestStream = ftpRequest.GetRequestStream();
                    requestStream.Write(fileContent, 0, fileContent.Length);
                    requestStream.Close();
                    FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
                    strMsg = "File Upload Status: " + response.ToString();
                    
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Resource Cleanup */
                ftpStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return strMsg;
 
        }
Posted
Updated 24-May-13 23:43pm
v3
Comments
Sunasara Imdadhusen 24-May-13 5:51am    
Use form submit method to post your multipart date
rajesh@1989 24-May-13 5:54am    
I do not understand what you want to say. I already added on web.config file.


Hello Rajesh,

Following are sample code. When clicking on submit button it will post selected files data to the mentioned (action) website.

HTML
<form id="Form1" action="htt://mysite.com/photo" method="post" enctype="multipart/form-data">
     <input id="myPhoto" name="myPhoto" type="file" />
     <input type="submit" />
</form>

Thanks,
Imdadhusen
 
Share this answer
 
Comments
rajesh@1989 24-May-13 6:11am    
I wrote following code on demo application use consume web service and web service is giving response like: Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.


<form id="form1" runat="server" action="http://MySiteAddress/FileTransfer.asmx/TransferFile" enctype="multipart/form-data">
<asp:FileUpload runat="server" id="fileArray"/>
<asp:Button ID="btnSubmit" runat="server" Text="Upload" onclick="btnSubmit_Click" />
<asp:Button ID="Button1" runat="server" önclick="Button1_Click" Text="Button" />
</form></pre>
rajesh@1989 24-May-13 6:46am    
Please give me some solution for it. It is very urgent as I am on stuck.
Thank you!!
Please check the answer - WCF service to accept a post encoded multipart/form-data[^].

This might help you.
 
Share this answer
 
Comments
rajesh@1989 28-May-13 15:13pm    
[ServiceContract]
public interface IFileUpload
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat=WebMessageFormat.Json,
UriTemplate = "/UploadedFiles/")]
void Upload(Stream data);
}
public class FileUpload : IFileUpload
{
public void Upload(Stream data)
{
StringBuilder sb = new StringBuilder();
try
{
string contentType = WebOperationContext.Current.IncomingRequest.ContentType;
if (!contentType.StartsWith("multipart/form-data; boundary="))
{
throw new ArgumentException("Error, invalid Content-Type: " + contentType);
}

MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1000];
int bytesRead = 0;
do
{
bytesRead = data.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
sb.AppendLine("Request size: " + ms.Position);
string boundary = contentType.Substring("multipart/form-data; boundary=".Length);
byte[] boundaryBytes = Encoding.ASCII.GetBytes(boundary);
byte[] requestBytes = ms.ToArray();
int index = 0;
Debug.Assert(requestBytes[0] == (byte)'-', "First char is '-'");
Debug.Assert(requestBytes[1] == (byte)'-', "Second char is '-'");
index = 2;
string boundaryLine = ReadLine(requestBytes, ref index);
Debug.Assert(boundaryLine == boundary, "First line is boundary");
string contentDispositionLine = ReadLine(requestBytes, ref index);
Debug.Assert(contentDispositionLine.StartsWith("Content-Disposition"), "First line of part is Content-Disposition");
sb.AppendLine(contentDispositionLine);
string contentTypeLine = ReadLine(requestBytes, ref index);
Debug.Assert(contentTypeLine.StartsWith("Content-Type"), "Second line of part is Content-Type");
sb.AppendLine(contentTypeLine);
string emptyLine = ReadLine(requestBytes, ref index);
Debug.Assert(emptyLine == "", "Third line is empty");
byte[] file = new byte[requestBytes.Length - index - "\r\n--".Length - boundaryBytes.Length - "--\r\n".Length];
Array.Copy(requestBytes, index, file, 0, file.Length);
File.WriteAllBytes(@"\UploadedFiles\a.txt", file);
sb.AppendLine("File saved to a.txt, len = " + file.Length);
}
catch (Exception e)
{
sb.AppendFormat("{0}: {1}", e.GetType().FullName, e.Message);
sb.AppendLine();
}
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
// return new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));
}
string ReadLine(byte[] buffer, ref int index)
{
StringBuilder sb = new StringBuilder();
while (index < buffer.Length - 1 && buffer[index] != 0x0D && buffer[index] != 0x0A)
{
sb.Append((char)buffer[index]);
index++;
}
index += 2;
return sb.ToString();
}
}
What is wrong in above code? is above works to accept multipart/form-data? Due to stream is used I cann't test it. It is not consuming through multipart/form-data by iphone. I am newbie in WCF Multipart/Form-data. Please help me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900