html文件上传函数
//fileupload.js
function select_upload(zurl, zmulti, callback) {
var zinput_file = document.createElement("input");
zinput_file.type = "file";
zinput_file.multiple = zmulti;
zinput_file.onchange = function (e) {
var form = new FormData();
for (var zi = 0; zi < zinput_file.files.length; zi++) {
form.append("file[" + zi.toString() + "]", zinput_file.files[zi]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.open("post", zurl);
xhr.send(form);
}
zinput_file.click();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="fileupload.js"></script>
</head>
<body>
<input type="button" value="上传文件" id="btnupload" onclick="upload_file();" />
<script type="text/javascript">
function upload_file() {
select_upload("upload.aspx", true, function (text) {
alert(text);
});
}
</script>
</body>
</html>
//upload.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace testfileupload
{
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > 0) {
string zpath = Server.MapPath("upload");
for (int i = 0; i < Request.Files.Count; i++) {
Request.Files[i].SaveAs(System.IO.Path.Combine(zpath, Request.Files[i].FileName));
}
}
Response.Write(Request.Files.Count.ToString() + "文件上传了");
}
}
}
复杂版本的上传js函数
function select_upload(zurl, zmulti, sucess_callback ,ztag_name,open_callback,error_callback) {
var zinput_file = document.createElement("input");
zinput_file.type = "file";
zinput_file.multiple = zmulti;
if (!ztag_name) {
ztag_name = "file";
}
zinput_file.onchange = function (e) {
var form = new FormData();
if (zmulti) {
for (var zi = 0; zi < zinput_file.files.length; zi++) {
form.append(ztag_name+"[" + zi.toString() + "]", zinput_file.files[zi]);
}
} else {
form.append(ztag_name, zinput_file.files[0]);
}
if (open_callback) {
open_callback("");
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
if (xhr.status == 200) {
sucess_callback(xhr.responseText);
}
} else {
if (error_callback) {
error_callback(xhr.status);
}
}
}
};
xhr.open("post", zurl);
xhr.send(form);
}
zinput_file.click();
}
浙公网安备 33010602011771号