HTML_文件上传+C#接受文件(使用WinForm桌面端作为远程服务器)

//使用文件选择器选取前端主机的文件(也可以直接指定路径)

<input type="file" id="Other" name="files" style="display:none" onchange="selectedFile(this)" multiple/>

获取选中的文件

function selectedFile(obj)//此处传入的参数是一个this指针,防止后端发送js到前端后找不到函数
{	
var fileslist=$("input[type='file']");
if(fileslist.length>0)
	{
		if(fileslist.get(0).files[0]!=undefined)
		{
			var Thefile=fileslist.get(0).files[0];
			if (Thefile) 
			{   
				var fileSize = 0;   
				if (Thefile.size > 1024 * 1024)   
					fileSize = (Math.round(Thefile.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';   
				else   
					fileSize = (Math.round(Thefile.size * 100 / 1024) / 100).toString() + 'KB';   
				$("#预览").val("已选择文件名:"+Thefile.name+";大小:"+fileSize);
			}
			else
			{
				alert("选择的文件名无效");
			}
		}
		else
		{
			alert("无法获取到选择的文件");
		}				
	}
}

上传:

function selectedFile(obj)
{
		var fileslist=$("input[type='file']");
		if(fileslist.length>0)
		{
			if(fileslist.get(0).files[0]!=undefined)
			{
				var Thefile=fileslist.get(0).files[0];
				var dict=new FormData();
				dict.append("fileName",Thefile.name);
				dict.append("fileContent",Thefile);
				dict.set("accept-charset","utf-8");
				document.charset='utf-8';
				$.ajax({
				url:USERNAME+";"+obj+";"+date+";"+startTime+";"+endTime,
				type:'post',
				data:dict,
				processData: false,// 不要处理数据
				contentType: 'text/json,charset=utf-8',
				dataType:'JSON',
				success:function (arg) {
					alert("上传成功");
					}
				})
			}
		}
		else
		{
		    alert("未得到任何有效文件:取消上传");
		}
	}

接收:

//取得请求的对象
HttpListenerRequest request = context.Request;
// 取得回应对象
HttpListenerResponse response = context.Response;
System.IO.Stream output = response.OutputStream;
string  recived = request.RawUrl;
var reader = new StreamReader(request.InputStream, Encoding.UTF8);
string msg = HttpUtility.UrlDecode(reader.ReadToEnd());
if (msg.Contains("WebKitFormBound"))
{
 	int index = msg.IndexOf("\r\n\r\n") + 4;
    int endindex = msg.IndexOf("------", 6);
    string getType = msg.Substring(index, endindex - index - 2).Split('.').Last();
    path = Data.FileFolderCheck(Data.FilePath + "\\UserData", currtUser) + "\\\\UserTest." + getType;
   //定义写文件流
   index = msg.IndexOf("\r\n\r\n", index + 4) + 4;
   endindex = msg.IndexOf("------", endindex + 6);
   string data = msg.Substring(index, endindex - index - 2);
   byte[] writeBytes = System.Text.Encoding.UTF8.GetBytes(data);
   File.WriteAllBytes(path, writeBytes);
   ConsoleUserColor.SetColorText(WhichWindow.LOGWindow, Color.YellowGreen, currtUser + "文件上传成功");
}

只能帮你们到这里了…
来自胖子东,开源、技术、共享

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值