美文网首页
上传文件到服务器端_C#

上传文件到服务器端_C#

作者: tjxy9rjxl3QP | 来源:发表于2017-10-16 16:23 被阅读0次

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

using System.Net;

using System.IO;

namespace www.xinduofen.cn

{

///

/// C#与http服务器端进行对接的工具类

///

class www.xinduofen.com

{

///

/// 用于缓存服务器端传输到客户端的SESSIONID或者JSESSIONID

///

private Cookie sessionidCookie = null;

///

/// 向HttpWebServer端上传文件(使用的是"post"方式)

///

/// 请求网址

/// 请求参数集合,无需参数时传入null值

/// 请求cookie集合,无需cookie时传入null值

/// 上传文件集合《控件名,上传文件的保存位置(包括"文件名"."扩展名")》,无需上传时传入null值

/// 返回请求结果字符串,返回为null代表请求失败

public String setFilesToHttpWebServer(String url, Hashtable data, CookieCollection cookies, Hashtable filesSaveAddress)

{

//用于缓存服务器端传输回来的结果字符串

string result = null;

if (string.IsNullOrEmpty(url))

{

return null;//传入参数异常

}

//用于分割信息部分的分隔符(不能与消息原文冲突)

String boundary = "HttpWebTool" + DateTime.Now.Ticks;

//结束分隔符数据流

byte[] andBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--");

//新行字符串数据流

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

try

{

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

//请求方式

req.Method = "POST";

//声明客户端只接收txt类型的内容

req.Accept = "text/plain";

//以消息的形式向服务器传递参数和数据流

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

//设置cookie盒子(客户端请求的cookie和服务器端返回的cookie就放在此盒子中)

CookieContainer cookieContainer = new CookieContainer();

if (sessionidCookie != null && !string.IsNullOrEmpty(sessionidCookie.Domain))

{

cookieContainer.Add(sessionidCookie);

}

if (cookies != null)

{

cookieContainer.Add(cookies);//添加调用者传入的cookie集合

}

req.CookieContainer = cookieContainer;

//用于累计数据流长度,初始化为0

long dataCount = 0;

byte[] parameterBytes = getParameterBytes(data, boundary);

if (parameterBytes != null && parameterBytes.Length>0)

{

//累计请求参数字符串数据流大小

dataCount += parameterBytes.Length;

}

//<控件名,上传文件的消息头部分字符流byte[]>

Hashtable uploadFileDeclareBytesSet = new Hashtable();

//如果有要上传的文件

if (filesSaveAddress != null && filesSaveAddress.Count > 0)

{

foreach (DictionaryEntry de in filesSaveAddress)

{

//如果将要上传的文件存在

if (File.Exists(de.Value.ToString()))

{

byte[] uploadFileDeclareBytes = getUploadFileDeclareBytes(de, boundary);

if (uploadFileDeclareBytes!=null)

{

//累计上传文件消息头部描述字符串数据流大小

dataCount += uploadFileDeclareBytes.Length;

//累计上传文件正文数据流大小

dataCount += new FileInfo(de.Value.ToString()).Length;

//累计新行字符串数据流数据流大小

dataCount += newline.Length;

uploadFileDeclareBytesSet.Add(de.Key.ToString(), uploadFileDeclareBytes);

}

}

}

}

//如果有数据流

if (dataCount>0)

{

//累计结束分隔符数据流大小

dataCount += andBoundary.Length;

//请求数据流的长度

req.ContentLength = dataCount;

using (Stream requestStream = req.GetRequestStream())

{

if (parameterBytes != null && parameterBytes.Length > 0)

{

requestStream.Write(parameterBytes, 0, parameterBytes.Length);

}

if (filesSaveAddress != null && filesSaveAddress.Count > 0)

{

foreach (DictionaryEntry de in filesSaveAddress)

{

if (File.Exists(de.Value.ToString()))

{

byte[] uploadFileDeclareBytes = (byte[])uploadFileDeclareBytesSet[de.Key.ToString()];

requestStream.Write(uploadFileDeclareBytes, 0, uploadFileDeclareBytes.Length);

using (FileStream fileStream = new FileStream(de.Value.ToString(), FileMode.Open, FileAccess.Read))

{

//建立字节组,并设置它的大小是多少字节

byte[] bytes = new byte[10240];

int n = -1;

while ((n = fileStream.Read(bytes, 0, bytes.Length)) > 0)

{

requestStream.Write(bytes, 0, n); //将指定字节的流信息写入文件流中

}

}

requestStream.Write(newline, 0, newline.Length);

}

}

}

requestStream.Write(andBoundary, 0, andBoundary.Length);

}

}

//接收返回值

using (HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse()) {

using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) {

result = reader.ReadToEnd().Trim();

}

if (myResponse.Cookies["SESSIONID"] != null)

{

sessionidCookie = myResponse.Cookies["SESSIONID"];

}

else

{

if (myResponse.Cookies["JSESSIONID"] != null)

{

sessionidCookie = myResponse.Cookies["JSESSIONID"];

}

}

}

}

catch (Exception)

{

Console.WriteLine("请查看传入参数是否正确或者服务器是否关闭");

}

return result;

}

///

/// 获得参数data的消息数据流,以"\r\n"结尾

///

/// 请求参数集合,无需参数时传入null值

/// 消息分隔符

/// 返回参数data的数据流,返回为空代表获得失败

private byte[] getParameterBytes(Hashtable data, String boundary)

{

byte[] parameterBytes = null;

//如果有请求参数

if (data != null && data.Count > 0)

{

string parameterStr = "";

foreach (DictionaryEntry de in data)

{

parameterStr += "--" + boundary;

parameterStr += "\r\n" + "Content-Disposition: form-data;name=\"" + de.Key.ToString() + "\"";

parameterStr += "\r\n" + "Content-Type: text/plain; charset=UTF-8";

parameterStr += "\r\n\r\n" + de.Value.ToString();

parameterStr += "\r\n";

}

if (!string.IsNullOrEmpty(parameterStr))

{

parameterBytes = Encoding.UTF8.GetBytes(parameterStr);//将上传字符串数据打包成数据流

}

}

return parameterBytes;

}

///

/// 获得上传文件的消息头部分字符流,以"\r\n\r\n"结尾

///

/// 上传文件《控件名,上传文件的保存位置(包括"文件名"."扩展名")》

/// 消息分隔符

/// 返回上传文件的消息头部分字符流,返回会为null代表获得失败

private byte[] getUploadFileDeclareBytes(DictionaryEntry de, String boundary)

{

byte[] uploadFileDeclareBytes = null;

//上传文件的消息头描述部分

string uploadFileDeclareStr = "";

uploadFileDeclareStr += "--" + boundary;

uploadFileDeclareStr += "\r\n" + "Content-Disposition: form-data;name=\"" + de.Key.ToString() + "\"; filename=\"" + de.Value.ToString() + "\"";

uploadFileDeclareStr += "\r\n" + "Content-Type: application/octet-stream";

uploadFileDeclareStr += "\r\n\r\n";

if (!string.IsNullOrEmpty(uploadFileDeclareStr))

{

uploadFileDeclareBytes = Encoding.UTF8.GetBytes(uploadFileDeclareStr);//将上传字符串数据打包成数据流

}

return uploadFileDeclareBytes;

}

}

}

内容所有权属于越康体育(专业从事体质测试仪,学生体质测试仪的研究)

相关文章

  • 上传文件到服务器端_C#

    using System; using System.Collections.Generic; using Sys...

  • 图片文件上传

    上传文件原理 上传文件,就是将文件从浏览器端传到服务器端; 上传文件,必须使用 标记来向服务器端发数据...

  • PHP文件上传

    1、文件上传原理 1)上传文件,就是将文件从浏览器端传到服务器端;2)上传文件,必须使用 标记来向服务器端发数据;...

  • PHP强化之13 - 文件上传与下载

    一、文件上传 将客户端文件上传到服务器端,再将服务器端的文件(临时文件)移动到指定目录即可。 1、form表单 文...

  • 文件上传和下载

    文件上传 文件上传涉及到前台页面的编写和后台服务器端代码的编写,前台发送文件,后台接收并保存文件,这才是一个完整的...

  • 文件上传(upload-labs详细全解)

    文件上传漏洞 常见的漏洞分类服务器配置不当导致文件上传开源编辑器存在上传漏洞本地文件上传限制可以上传被绕过服务器端...

  • TFTP:实现简单文本传输协议的上传功能

    上一节我们开发的客户端能成功的从服务器端下载文件,本节我们完成相反功能,实现客户端向服务器端上传文件。文件上传与下...

  • Django文件上传

    本篇主要讲的是ajax下的文件上传 模板html文件内容 编写文件上传js 服务器端视图代码如下 POST提交过来...

  • 12.4.2 文件上传的处理

    12.4.2 文件上传的处理 在服务器端通过PHP处理上传 上传文件的接收和处理是通过PHP脚本来处理的,具体需要...

  • Web应用安全之文件上传漏洞详解

    什么是文件上传漏洞 文件上传漏洞是在用户上传了一个可执行的脚本文件,本通过此脚本文件获得了执行服务器端命令的功能,...

网友评论

      本文标题:上传文件到服务器端_C#

      本文链接:https://www.haomeiwen.com/subject/wntluxtx.html