js
<!doctype html> <html> <head> <meta charset="utf-8"> <title>js上传图片</title> </head> <body> <input id="file" type="file"> <script type="text/javascript"> window.onload = function myfunction() { var input = document.getElementById(‘file‘); input.onchange = function () { var files = this.files; for (var i = 0, len = files.length; i < len; i++) { var file = files[i]; //file.name || file.fileName => 文件名称 //file.size || file.fileSize => 文件大小 upload_html5(file); } }; } function upload_html5(file) { //html5 上传 var xhr = new XMLHttpRequest(); //上传进度事件 xhr.upload.addEventListener("progress", function (e) { }, false); //上传完成(成功)事件 xhr.addEventListener("load", function (e) { //获取服务器响应 var obj = JSON.parse(e.target.responseText); if (obj.code == 200) { alert("上传成功"); } else { alert(obj.message); } }, false); //上传失败事件 xhr.addEventListener("error", function (e) { console.log(e); alert("上传失败"); }, false); //上传中断(取消)事件 xhr.addEventListener("abort", function (e) { alert("上传取消"); }, false); var fd = new FormData; //添加要上传的文件对象 fd.append("file", file); fd.append("hallName", ‘分会场1‘); fd.append("dateTime", ‘2019-06-21‘); xhr.open("POST", "/Common/UploadFile"); xhr.send(fd); } </script> </body> </html>
public ActionResult UploadFile() { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var directory = string.Format("{0}/Upload/{1}/", baseDirectory, Request.Form["hallName"]); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); var filePath = string.Format("{0}/{1}.jpg", directory, Request.Form["dateTime"]); Request.Files[0].SaveAs(filePath); return Json(new Response()); }
原文地址:https://www.cnblogs.com/kikyoqiang/p/11064841.html
时间: 2024-10-09 15:14:21