//使用文件选择器选取前端主机的文件(也可以直接指定路径)
<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 + "文件上传成功");
}
只能帮你们到这里了…
来自胖子东,开源、技术、共享