方法一、通过Ajax方式上传文件(input file),使用FormData进行Ajax请求
<
div
>
<
input
type="file" name="FileUpload" id="FileUpload">
<
a
class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</
a
>
</
div
>
<script type=
"text/jscript"
>
$(
function
() {
$(
"#btn_uploadimg"
).click(
function
() {
var
fileObj = document.getElementById(
"FileUpload"
).files[0];
// js 获取文件对象,(据说IE8 不支持.files写法,未测试)
if
(
typeof
(fileObj) ==
"undefined"
|| fileObj.size <= 0) {
alert(
"请选择图片"
);
return
;
}
var
formFile =
new
FormData();
formFile.append(
"action"
,
"UploadVMKImagePath"
);
formFile.append(
"file"
, fileObj);
//加入文件对象
//第一种 XMLHttpRequest 对象
//var xhr = new XMLHttpRequest();
//xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
//xhr.onload = function () {
// alert("上传完成!");
//};
//xhr.send(formFile);
//第二种 ajax 提交
var
data = formFile;
$.ajax({
url:
"/Admin/Ajax/VMKHandler.ashx"
,
data: data,
type:
"Post"
,
dataType:
"json"
,
cache:
false
,
//上传文件无需缓存
processData:
false
,
//用于对data参数进行序列化处理 这里必须false
contentType:
false
,
//必须
success:
function
(result) {
alert(
"上传完成!"
);
},
})
})
})
</script>
<form id="fmFileUpload_Knowledge" method="post" enctype="multipart/form-data">
//必须要有name属性,name属性是用于在前台和后台间建立联系的,form中只有具有name属性的控件,其值才会被传递到后台,而没有name属性的控件后台程序是接收不到它的值的
<input id="UploadFile" type="file" name="name1" /></div>
</form>
<script type=
"text/jscript"
>
$(
function
() {
$(
"#btn_uploadimg"
).click(
function
() {
var options = { type: 'post', data: { Default: "FileUpload",}, url: 'Index.aspx', success: function (data) {
//兼容IE和FireFox var file = $("#UploadFile"); file.after(file.clone().val("")); file.remove();
} }; $('#fmFileUpload_Knowledge').ajaxSubmit(options);
})
})
</script>
private string FileUpload() { string fileName = string.Empty; string serverPath = string.Empty; try { HttpFileCollection httpFileCollection = Request.Files; if (httpFileCollection.Count > 0) //如果没有name属性,获取不到file { HttpPostedFile file = httpFileCollection[0];
fileName = Path.GetFileName(file.FileName);
if (File.Exists(serverPath)) { rdsl.returnMessage = "该文件已存在,请更改文件名或者删除原文件,然后上传."; return GetJSON.JSONSerialize(rdsl); }
Thread thread = new Thread(new ThreadStart(() => { file.SaveAs(serverPath); } )); thread.Start();
} else { rdsl.returnCode = iCode.ToString(); rdsl.returnMessage = "未获取到文件.";
} return GetJSON.JSONSerialize(rdsl);
} catch (Exception ex) { log.Error(ex.Message); log.Error(ex.StackTrace);
}
}
/// <summary> /// 下载文件方法 /// </summary> /// <param name="serverPath">被下载的文件地址(服务器地址包括文件)</param> /// <param name="filePath">另存放的路径(本地需要存储文件的文件夹地址)</param> public void Download(string serverPath, string filePath) { WebClient client = new WebClient(); string fileName = serverPath.Substring(serverPath.LastIndexOf("/") + 1); ;//被下载的文件名 string path = filePath + fileName;//另存为地址 try { WebRequest myre = WebRequest.Create(serverPath); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } try { client.DownloadFile(serverPath, fileName); FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); byte[] mbyte = r.ReadBytes((int)fs.Length); FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fstr.Write(mbyte, 0, (int)fs.Length); fstr.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } }