0

我已经浏览并按照以下方式将多个文件发布到 serverlet 页面,但未能做到这一点 https://stackoverflow.com/questions/18958488/uploading-multiple-files-from-aspx-to-servelet-page-through- http-post-method-is 我通过 http post 方法将多个文件从 .Net 应用程序发布到 Java Servelet 页面,我收到错误:N~java.io.IOException: Corrupt form data: noleading boundary: != - -----------------------------------------8d08693613639c3

Can any body please & please help me out:
my code is



      public int postenrollments(string source, string posturl)
        {

            string[] enrolldirect;
            int FindDirectoriesLength=System.IO.Directory.GetDirectories(source).Length ;
            string SuccessUploadedFiles = ConfigurationManager.AppSettings.Get("UploadedEnrollmentsSource");
            if (FindDirectoriesLength == 0)
            {
                status = 0;
            }
            else
            {
                enrolldirect = Directory.GetDirectories(source).ToArray();
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(posturl);

                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("stTerminal", "000018112");
                nvc.Add("stAgentID", "13220001");
                nvc.Add("stvendorId", "112");

                posturl += "?stTerminal=" + "000018112" + "&stAgentID=" + 13220001 + "&stvendorId=" + 112;
                foreach (string dir in enrolldirect)
                {
                    if (VerifyFiles(dir))
                    {
                        string[] enrollfiles = Directory.GetFiles(dir).ToArray();
                        UploadFile[] files = new UploadFile[enrollfiles.Length];
                        string[] filestoUpload = new string[enrollfiles.Length]; //This For PostMultipleFiles & UploadFilesToRemoteUrl Method
                        for (int i = 0; i < enrollfiles.Length; i++)
                        {
                            filestoUpload[i] = enrollfiles[i];//This For PostMultipleFiles & UploadFilesToRemoteUrl Method
                            files[i] = new UploadFile(enrollfiles[i]);
                        }
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(posturl); 
                        HttpWebResponse resp = UploadFilesToRemoteUrl(posturl, filestoUpload, "", nvc); 
                        StreamReader respreader = new StreamReader(resp.GetResponseStream());
**//Here in response I am getting the boundary exception**
                        string response = respreader.ReadToEnd();                     
                }
            }
            return status;
        }

用于发布文件的方法

public HttpWebResponse UploadFilesToRemoteUrl(string url, string[] files, string logpath, NameValueCollection nvc)
        {     
         HttpWebResponse webResponse21;
        long length = 0;
        string boundary = "--------------"+DateTime.Now.Ticks.ToString("x");            
        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" +boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.KeepAlive = true;
        httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;    
    Stream memStream = new System.IO.MemoryStream();
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +boundary + "\r\n");
    string formdataTemplate = "\r\n--" + boundary +"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
    foreach (string key in nvc.Keys)
    {
        string formitem = string.Format(formdataTemplate, key, nvc[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        memStream.Write(formitembytes, 0, formitembytes.Length);
    }
    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
    for (int i = 0; i < files.Length; i++)
    {
        string header = string.Format(headerTemplate, "file" + i, files[i]);
        //string header = string.Format(headerTemplate, "uplTheFile", files[i]);  
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        memStream.Write(headerbytes, 0, headerbytes.Length);
        FileStream fileStream = new FileStream(files[i], FileMode.Open,FileAccess.Read);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        memStream.Write(boundarybytes, 0, boundarybytes.Length);
        fileStream.Close();
    }
    httpWebRequest2.ContentLength = memStream.Length;
    Stream requestStream = httpWebRequest2.GetRequestStream();
    memStream.Position = 0;
    byte[] tempBuffer = new byte[memStream.Length];
    memStream.Read(tempBuffer, 0, tempBuffer.Length);
    memStream.Close();
    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
    requestStream.Close();
     webResponse21 = (HttpWebResponse)httpWebRequest2.GetResponse();
     return webResponse21;
    }
4

1 回答 1

0
*Friends,At last I have got the sucessfull solution,First Let me explain what was the Problem was..
The Problem was in building multipart request body in .net function to send to servelet page,The page in which I was sending the files was strictly programmed to take files with only multipart request format.*

*The new function and the classes which I am using to post the files are:*

PostMultipleFilesToServelet 的函数:

  public static HttpWebResponse Upload(HttpWebRequest req, UploadFile[] files, NameValueCollection form)

    {

    List<MimePart> mimeParts = new List<MimePart>();

    try

    {

    foreach (string key in form.AllKeys)

    {

    StringMimePart part = new StringMimePart();

    part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\"";

    part.StringData = form[key];

    mimeParts.Add(part);

    }

    int nameIndex = 0;

    foreach (UploadFile file in files)

    {

    StreamMimePart part = new StreamMimePart();

    if (string.IsNullOrEmpty(file.FieldName))

    file.FieldName = "file" + nameIndex++;

    part.Headers["Content-Disposition"] = "form-data; name=\"" + file.FieldName + "\"; filename=\"" + file.FileName + "\"";

    part.Headers["Content-Type"] = file.ContentType;

    part.SetStream(file.Data);

    mimeParts.Add(part);

    }

    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");

    req.ContentType = "multipart/form-data; boundary=" + boundary;

    req.Method = "POST";

    long contentLength = 0;

    byte[] _footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");

    foreach (MimePart part in mimeParts)

    {

    contentLength += part.GenerateHeaderFooterData(boundary);

    }

    req.ContentLength = contentLength + _footer.Length;

    byte[] buffer = new byte[8192];

    byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");

    int read;

    using (Stream s = req.GetRequestStream())

    {

    foreach (MimePart part in mimeParts)

    {

    s.Write(part.Header, 0, part.Header.Length);

    while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)

    s.Write(buffer, 0, read);

    part.Data.Dispose();

    s.Write(afterFile, 0, afterFile.Length);

    }

    s.Write(_footer, 0, _footer.Length);

    }

    return (HttpWebResponse)req.GetResponse();

    }

    catch

    {

    foreach (MimePart part in mimeParts)

    if (part.Data != null)

    part.Data.Dispose();

    throw;

    }

    }

The Classes Used Are:
**StringMimePart.cs**

   using System;

    using System.Collections.Generic;

    using System.Text;

    using System.IO;

    namespace UploadHelper

    {

    public class StringMimePart : MimePart

    {

    Stream _data;

    public string StringData

    {

    set

    {

    _data = new MemoryStream(Encoding.UTF8.GetBytes(value));

    }

    }

    public override Stream Data

    {

    get

    {

    return _data;

    }

    }

    }

    }

**StreamMimePart.cs**

 

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace UploadHelper

{

public class StreamMimePart : MimePart

{

Stream _data;

public void SetStream(Stream stream)

{

_data = stream;

}

public override Stream Data

{

get

{

return _data;

}

}

}

}

**UploadFile.cs**

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace UploadHelper

{

public class UploadFile

{

Stream _data;

string _fieldName;

string _fileName;

string _contentType;

public UploadFile(Stream data, string fieldName, string fileName, string contentType)

{

_data = data;

_fieldName = fieldName;

_fileName = fileName;

_contentType = contentType;

}

public UploadFile(string fileName, string fieldName, string contentType)

: this(File.OpenRead(fileName), fieldName, Path.GetFileName(fileName), contentType)

{ }

public UploadFile(string fileName)

: this(fileName, null, "application/octet-stream")

{ }

public Stream Data

{

get { return _data; }

set { _data = value; }

}

public string FieldName

{

get { return _fieldName; }

set { _fieldName = value; }

}

public string FileName

{

get { return _fileName; }

set { _fileName = value; }

}

public string ContentType

{

get { return _contentType; }

set { _contentType = value; }

}

}

}

**No Let Us Send the Files from any directory and read the response:**


 string[] enrolldirect = Directory.GetDirectories("C://YourDirectoryPathInWhichYouHaveFilesToPost").ToArray();
 //Building webrequest to your url (might be servlet or other)
   HttpWebRequest webreq =    (HttpWebRequest)WebRequest.Create("http://www.IamMohdIlyasFromHyderabadIndia.WriteYourServeletUrlToWhomeYouAreUploadingFiles");
  NameValueCollection nvc = new NameValueCollection();
 //If you required then only pass it else don't pass and remove it from function too
  nvc.Add("YourNVCName1", "YourNVCValue1");
  nvc.Add("YourNVCName2", "YourNVCValue2");
  string[] enrollfiles = Directory.GetFiles(dir).ToArray();
  UploadFile[] files = new UploadFile[enrollfiles.Length];
  for (int i = 0; i < enrollfiles.Length; i++)
  {
  files[i] = new UploadFile(enrollfiles[i]);
  }
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(posturl);
  HttpWebResponse resp = HttpUploadHelper.Upload(req, files, nvc);
  StreamReader respreader = new StreamReader(resp.GetResponseStream());
  //Now read the Response..Enjoy....
  string response = respreader.ReadToEnd();
于 2013-09-25T11:45:23.283 回答