刚实习的时候遇到一个问题:上传文件的URL有特定格式限制,需要按格式定义头信息,才能上传成功。查资料时候当时好像是java版本的,C#代码贴上。
//uploadFile:上传文件名 groupId:GUID public string FileUpload(string uploadFile, string groupId) { //从流中读取字节块并将该数据写入给定缓冲区buffer中 FileStream fileStream = new FileStream(uploadFile, FileMode.Open, FileAccess.Read); Byte[] buffer = new Byte[fileStream.Length]; fileStream.Read(buffer, 0, Convert.ToInt32(fileStream.Length)); //boundary setting string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); string fileName = Path.GetFileName(uploadFile); string nameOnly = fileName.Substring(0, fileName.LastIndexOf(".")); Dictionary<string, string> Params = new Dictionary<string, string>(); Params.Add("name", fileName); Params.Add("groupId", groupId); Params.Add("appModule", "portal"); Params.Add("filePath", ""); Params.Add("thumbnail", "true"); Params.Add("storeType", "1"); Params.Add("property1", ""); Params.Add("property2", ""); Params.Add("property3", ""); Params.Add("property4", ""); Params.Add("property5", ""); Params.Add("flag", "false"); StringBuilder sb = new StringBuilder(); //发送必要字段 foreach (KeyValuePair<string, string> param in Params) { sb = sb.Append("--"); sb = sb.Append(boundary); sb = sb.Append("\r\n"); sb = sb.Append("Content-Disposition: form-data; name=\"" + param.Key + "\"\r\n\r\n"); sb = sb.Append(param.Value); sb = sb.Append("\r\n"); } //要发送的文件 sb = sb.Append("--"); sb = sb.Append(boundary); sb = sb.Append("\r\n"); sb = sb.Append("Content-Disposition: form-data; name=\"" + nameOnly + "\"; filename=\"" + fileName + "\"\r\n"); sb = sb.Append("Content-Type: application/octet-stream\r\n\r\n"); byte[] data = Encoding.Default.GetBytes(sb.ToString()); byte[] end_data = Encoding.Default.GetBytes(("\r\n--" + boundary + "--\r\n")); Uri uri = new Uri("上传文件地址"); HttpWebRequest webRequset = (HttpWebRequest)WebRequest.Create(uri); webRequset.ContentType = "multipart/form-data; boundary=" + boundary; webRequset.Method = "POST"; //长度属性:头+文件流+尾的长度 long length = data.Length + buffer.Length + end_data.Length; webRequset.ContentLength = length; Stream requestStream = webRequset.GetRequestStream(); //将拼接的数据和文件流写入 requestStream.Write(data, 0, data.Length); requestStream.Write(buffer, 0, buffer.Length); requestStream.Write(end_data, 0, end_data.Length); //获取返回信息 WebResponse responce = webRequset.GetResponse(); Stream responeStream = responce.GetResponseStream(); StreamReader sr = new StreamReader(responeStream); return sr.ReadToEnd(); }
时间: 2024-12-21 23:18:17