使用c#的HttpWebRequst的post方法上传文件时,文件的filename传不到服务器的那边,服务器那边是用python语言来写的request.FILES.has_key('user_design_file.zip')是false,c#这边的代码是什么原因呢,谢谢。
c#的代码如下public object UserDesignFileUpload(string fileDirectory, NameValueCollection url, /*string zipedFile,*/ /*string contentType, CookieContainer cookie,*/string fileUploadType)
        {
            
            string zipedFloderName = fileDirectory.Substring(fileDirectory.LastIndexOf("/") + 1) + ".zip";            string zipedFileLocation = "d:/" + zipedFloderName;            Zip(fileDirectory, zipedFileLocation, 4096, 1);            string postUrl = WebUrlCollection.Prefix + WebUrlCollection.GetValueCollection()[fileUploadType];
                     
            if (zipedFloderName == null || zipedFloderName.Length == 0)
            {
                string defaultDirectory = Directory.GetCurrentDirectory() + "\\";
                zipedFloderName = "";
            }            
            Uri uri = new Uri(postUrl);            string boundary = DateTime.Now.Ticks.ToString("x");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                       request.ContentType = "\r\nmultipart/form-data; boundary=" + boundary;            request.Method = "Post";
            request.Timeout = 30000;
            request.KeepAlive = true;            StringBuilder builder = new StringBuilder();            if (url != null)
            {
                foreach (string key in url)
                {
                    builder.Append("--" + boundary + "boundary +\r\nContent-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + url[key] + "\r\n");
                }
            }            builder.Append("--" + boundary + "\r\nContent-Disposition: form-data; name=\"fileupload\";");
            builder.Append("filename=\"");
                        builder.Append(Path.GetFileName(zipedFileLocation));            builder.Append("\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            string postHeater = builder.ToString();            byte[] postHeaterBytes = Encoding.UTF8.GetBytes(postHeater);            byte[] boundayBytes = Encoding.ASCII.GetBytes(boundary);
            FileStream fileStream = new FileStream(zipedFileLocation, FileMode.Open, FileAccess.Read, FileShare.None);
            long length = postHeaterBytes.Length + fileStream.Length + boundayBytes.Length;            request.ContentLength = length;            Stream requestStream = request.GetRequestStream();           
            try
            {
                // Write out post header.
                requestStream.Write(postHeaterBytes, 0, postHeaterBytes.Length);                // Write out the file contents.
                byte[] buffer = new Byte[(uint)Math.Min(4096, (int)fileStream.Length)];                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }                // Write out the trailing boundary.
                requestStream.Write(boundayBytes, 0, boundayBytes.Length);            }
            catch (WebException e)
            {
                return e.ToString();
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            StringBuilder responseData = new StringBuilder();           
            responseData.Append(reader.ReadLine());
            responseStream.Close();            responseData.Replace("/*", " ");
            responseData.Replace("*/", " ");
            Debug.WriteLine("file upload design:"+responseData.ToString());
            return handleResponseData(responseData.ToString());
        }        /// <summary>
        /// Encryptions the description.
        /// Analysis the description
        /// </summary>
        /// <param name="description">The description.</param>
        /// <returns></returns>
        public string EncryptionDescription(string description) {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();            string encrytDesc = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.ASCII.GetBytes(description)));
            return encrytDesc;
        }        /// <summary>
        /// Users the desigin directory.
        /// send the data by get method!
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="sessionId">The session id.</param>
        public object UserDesiginDirectory(string url,string sessionId) {
            if(UserLogin == null){
                Debug.WriteLine("user has not login,please login again.");                throw new Exception("user has not login,please login again!");
            }            //string postUrl = url + "s = " + sessionId
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sessionId);
            string postData =url+ HttpUtility.UrlEncode(bytes);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postData);            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            Stream stream = response.GetResponseStream();            StreamReader reader = new StreamReader(stream);            StringBuilder builder = new StringBuilder();
            if(reader.ReadLine() != null){
                builder.Append(reader.ReadLine());
            }
           return handleResponseData(builder.ToString());
           
        }没有积分了,请大家帮帮吗,谢谢

解决方案 »

  1.   


    namespace WebInterface.FileOperation
    {
        public class UpLoadFile
        {
            public Login.Login UserLogin;
            public string fileSuffixes = ".zip";
            private NameValueCollection nameValueCollection = new NameValueCollection();        public UpLoadFile()
            {
                nameValueCollection.Add("ProductModel", "/client/product/savemodel/");
                nameValueCollection.Add("UserDesign", "/client/design/save/");
            }        /// <summary>
            /// Zips the specified ziped floder.upload the file and compress the file,the prefix is .zip
            /// </summary>
            /// <param name="zipedFloder">The ziped floder.the floder needs to be compress and ziped name is as same as it</param>
            /// <param name="zipFile">The zip file.</param>
            /// <param name="compressionLevel">The compression level.</param>
            /// <param name="blockSize">Size of the block.</param>
            public String Zip(string zipedFloder, string zipFile, int compressionLevel, int blockSize)
            {            if (!Directory.Exists(zipedFloder))
                {
                    throw new Exception("The ziped file is not existed!");
                }            // Crc32 crc = new Crc32();
                string[] fileNames = Directory.GetFiles(zipedFloder);
                string splitString = null;            ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(zipFile));            zipOutputStream.SetLevel(6);
                foreach (string file in fileNames)
                {
                    splitString = file.Substring(file.LastIndexOf("/") + 1);
                    FileStream fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);                ZipEntry entry = new ZipEntry(splitString);
                    entry.Size = fs.Length;                fs.Close();
                    //crc.Reset();
                    // crc.Update(buffer);
                    //entry.Crc = crc.Value;
                    zipOutputStream.PutNextEntry(entry);
                    zipOutputStream.Write(buffer, 0, buffer.Length);
                }            zipOutputStream.Finish();
                zipOutputStream.Close();            return zipFile;
            }        /// <summary>
            /// Handles the response data.
            /// </summary>
            /// <param name="data">The data.</param>
            /// <returns></returns>
            private object handleResponseData(string data)
            {
                object obj = null;
                JObject jobject = JObject.Parse(data);
                if (data.IndexOf(ErrorStatus.Result.fail.ToString()) != -1)
                {
                    obj = new JsonSerializer().Deserialize(new JsonTokenReader(jobject), typeof(ErrorMessage));
                }
                else if (data.IndexOf(ErrorStatus.Result.ok.ToString()) != -1)
                {
                    obj = new JsonSerializer().Deserialize(new JsonTokenReader(jobject), typeof(DesignFileUpLoad));            }
                return obj;
            }
            /// <summary>
            /// Ups the load.
            /// </summary>
            /// <param name="fileDirectory">The upload file.</param>
            /// <param name="url">The URL.url should include 2 parameters
            ///                     <session_id>session_id</session_id>
            ///                     <description>description</description>
            /// </param>
            /// <param name="zipedFloderName">Name of the file for.</param>
            /// <param name="contentType">Type of the content.</param>
            /// <param name="queryString">The query string.</param>
            /// <param name="cookie">The cookie.</param>
            public object UserDesignFileUpload(string fileDirectory, NameValueCollection url, /*string zipedFile,*/ /*string contentType, CookieContainer cookie,*/string fileUploadType)
            {            string zipedFloderName = fileDirectory.Substring(fileDirectory.LastIndexOf("/") + 1) + ".zip";            string zipedFileLocation = "d:/" + zipedFloderName;            Zip(fileDirectory, zipedFileLocation, 4096, 1);            string postUrl = WebUrlCollection.Prefix + WebUrlCollection.GetValueCollection()[fileUploadType];            if (zipedFloderName == null || zipedFloderName.Length == 0)
                {
                    string defaultDirectory = Directory.GetCurrentDirectory() + "\\";
                    zipedFloderName = "user_design_file";
                }
                Uri uri = new Uri(postUrl);            string boundaryValue = /*new String('-', 24) +*/ DateTime.Now.Ticks.ToString("x");
                string boundary = "--"+boundaryValue;
                //string boundary = DateTime.Now.Ticks.ToString("x");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;            request.Method = "Post";
                request.KeepAlive = true;            StringBuilder builder = new StringBuilder();            if (url != null)
                {
                    foreach (string key in url)
                    {
                        builder.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + url[key] + "\r\n");
                    }
                }            builder.Append(boundary + "\r\nContent-Disposition: form-data; name=\"user_design_file\"; ");
                builder.Append("filename=\"");            builder.Append(zipedFileLocation);            builder.Append("\"\r\nContent-Type: text/plain\r\n\r\n");
                string postHeader = builder.ToString();            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);            //byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "\r\n");
                byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
                FileStream fileStream = new FileStream(zipedFileLocation, FileMode.Open, FileAccess.Read, FileShare.None);
                long length = postHeaderBytes.Length + fileStream.Length + boundayBytes.Length;            request.ContentLength = length;            Stream requestStream = request.GetRequestStream();            try
                {
                    requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);                byte[] buffer = new Byte[(uint)Math.Min(4096, (int)fileStream.Length)];                int bytesRead = 0;
                    StringBuilder testbuilder = new StringBuilder();
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }                requestStream.Write(boundayBytes, 0, boundayBytes.Length);            }
                catch (WebException e)
                {
                    return e.ToString();
                }
                finally
                {
                    if (requestStream != null)
                    {
                        requestStream.Close();
                    }
                }            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                StringBuilder responseData = new StringBuilder();
                responseData.Append(reader.ReadLine());
                responseStream.Close();            responseData.Replace("/*", " ");
                responseData.Replace("*/", " ");
                Debug.WriteLine("response data:" + responseData.ToString());
                return handleResponseData(responseData.ToString());
            }    }
    }
    整个文件上传的过程,测试已经通过。需要注意的是boundary的格式的使用,链接如下:
    http://www.faqs.org/rfcs/rfc1867.html