使用HttpWebRequest发送文件

3

你好,我正在尝试使用Web服务从一个文件夹发送XML文件到本地计算机的另一个文件夹, 文件已成功发送并且应用程序已正常关闭,但问题是文件在目标文件夹中需要很长时间才能修改,当我再次尝试调用Web服务时,它会给我超时异常。 以下是我的代码:

public void SendC_XML(string path, string queueID, string application, string servicewTMURI)
    {


        HttpWebRequest httpWebRequest2 = null;
        //Stream memStream = null;
        //FileStream fileStream = null;

        String[] listOfFiles = Directory.GetFiles(path, "*.xml");






        for (int i = 0; i < listOfFiles.Length; i++)
        {
            try
            {
                MyLog.Add("found path " + listOfFiles[i]);

                string[] ImagesArray = listOfFiles[i].Split('\\');
                string ImageName = ImagesArray[ImagesArray.Length - 1];
                int index = ImageName.IndexOf(".");
                if (index > 0)
                    ImageName = ImageName.Substring(0, index);


                MyLog.Add("image name = " + ImageName);


                string[] textArray1 = new string[] { servicewTMURI, "/Queue/SetFile/", application, "/", queueID, "/" + ImageName + "/xml" };
                string requestUriString = string.Concat(textArray1);

                Guid guid = new Guid();
                string boundary = "---------------------------" + guid;



                httpWebRequest2 = (HttpWebRequest)WebRequest.Create(requestUriString);
                httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
                boundary;
                MyLog.Add("ContentType = " + httpWebRequest2.ContentType);

                httpWebRequest2.Method = "POST";
                httpWebRequest2.KeepAlive = false;
                httpWebRequest2.Timeout = 5000;
                httpWebRequest2.Proxy = null;

                httpWebRequest2.ServicePoint.ConnectionLeaseTimeout = 5000;
                httpWebRequest2.ServicePoint.MaxIdleTime = 5000;

                httpWebRequest2.Credentials =
                System.Net.CredentialCache.DefaultCredentials;


                using (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}";






                    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++)
                    //{

                    //MyLog.Add("file = " + files[i]);
                    string header = string.Format(headerTemplate, "uplTheFile", listOfFiles[i]);

                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                    memStream.Write(headerbytes, 0, headerbytes.Length);

                    using (FileStream fileStream = new FileStream(listOfFiles[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;

                    using (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();

                    }
                    //httpWebRequest2.Abort();
                    httpWebRequest2 = null;

                    //webResponse2 = null;

                }


            }
            catch (Exception ex)
            {
                MyLog.Add("error in cXML method = " + ex.Message);
            }
            finally
            {
                //memStream.Close();
                //fileStream.Close();
                //requestStream.Close();

                try
                {
                    if (httpWebRequest2 != null)
                    {
                        MyLog.Add("heeeeeeeeeeeeeeey request != null");
                        httpWebRequest2.GetRequestStream().Close();
                        httpWebRequest2 = null;
                    }

                }
                catch (Exception exception2)
                {
                    throw exception2;
                }

            }




        }

    }
1个回答

3
您可以使用此功能通过多部分表单数据上传文件,如果无法正常工作,请展示您实现的接收文件服务的方式。
public void Upload(string uri, string filePath)
{   
    string formdataTemplate = "Content-Disposition: form-data; filename=\"{0}\";\r\nContent-Type: image/jpeg\r\n\r\n";
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.ServicePoint.Expect100Continue = false;
    request.Method = "POST";
    request.ContentType = "multipart/form-data; boundary=" + boundary;

    using(FileStream fileStream    = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));   
            byte[] formbytes = Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formbytes, 0, formbytes.Length);
            byte[] buffer = new byte[1024 * 4];
            int bytesLeft = 0;

            while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                requestStream.Write(buffer, 0, bytesLeft);
            }

        }
    }

    try
    {           
        using (HttpWebResponse response    = (HttpWebResponse)request.GetResponse()) { }

        Console.WriteLine ("Success");
    }
    catch (Exception ex)
    {
        throw;
    }
}

但是目标文件夹中的文件为空 :( - user1814595
字符串formdataTemplate = "Content-Disposition: form-data; filename="{0}";\r\nContent-Type: text/xml\r\n\r\n"; - Aydin
文件仍然为空。 - user1814595
我没有 Web 服务源代码,只能使用它。 我尝试进行调试并发现了错误:
  • $exception {"远程服务器返回错误:(500) 内部服务器错误。"} System.Exception {System.Net.WebException}
- user1814595
让我们在聊天中继续这个讨论 - user1814595
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接