C# 用原生JS进行文件的上传

1.此文章是用原生JS来进行文件的上传,有两个版本,一个不用ajax,一个用ajax。

1)非AJAX

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body> <form id="upload-form" action="Template/UploadBusinessImage" method="post" enctype="multipart/form-data">
<input type="file" id="upload" name="ProductImage"/> <br/>
<input type="submit" value="上传"/>
</form> </body>
</html>

2)AJAX

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8"/>
<script>
/*原生JS版*/
function updateFile() {
/* FormData 是表单数据类 */
var fd = new FormData();
var ajax = new XMLHttpRequest();
fd.append("upload", 1);
/* 把文件添加到表单里 */
fd.append("ProductImage", document.getElementById("upfile").files[0]);
ajax.open("post", "Template/UploadBusinessImage", true); ajax.onload = function () {
console.log(ajax.responseText);
};
ajax.send(fd);
} </script>
</head>
<body>
<p><input type="file" id="upfile"></p>
<p><input type="button" id="upJS" value="用原生JS上传" onclick="updateFile()"></p>
</body>
</html>

2. 后台

        public ActionResult UploadBusinessImage(HttpPostedFileBase ProductImage)
{ string error = "";
try
{
//文件上传
HttpPostedFileBase postFileBase = ProductImage; //文件后缀
string extension = Path.GetExtension(postFileBase.FileName); //文件流
Stream uploadStream = postFileBase.InputStream; //把文件写入到本地E盘
using (var fileStream = System.IO.File.Create("E:\\" + postFileBase.FileName))
{
uploadStream.Seek(0, SeekOrigin.Begin);
uploadStream.CopyTo(fileStream);
} return this.Json(error, JsonRequestBehavior.AllowGet); }
catch (Exception e)
{
return this.Json(e.Message, JsonRequestBehavior.AllowGet);
}
}
上一篇:knowledge learning things TODO


下一篇:【Java每日一题】20161215