標籤:
1 <div id="div1">2 <input type="file" id="uploadfile" style="width: 100px; height: 25px;" />3 <input id="b1" type="button" value="上傳" style="display: inline-block; width: 40px; height: 25px;" />4 </div>
js指令碼:
https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html
http://dev.w3.org/2006/webapi/FileAPI/
1 window.onload = function () { 2 document.getElementById("uploadfile").addEventListener("change", function () { 3 //1、擷取所選的檔案 暫時只選一個 4 5 var filereader = new FileReader(); 6 filereader.onloadend = function (event) { 7 console.log("a"); 8 var filedata = event.target.result; 9 var request = new XMLHttpRequest();10 request.open("POST", "Handler1.ashx", true);11 var formdata = new FormData();12 formdata.append(file.name, file);13 request.send(formdata);14 }15 filereader.onloadstart = function (event) {16 console.log("b");17 18 }19 var file = document.getElementById("uploadfile").files[0];20 var fileblob = filereader.readAsArrayBuffer(file);21 }, true);22 }
C#
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Text; 6 using System.IO; 7 using System.Data; 8 namespace WebApplication1 9 {10 /// <summary>11 /// Handler1 的摘要說明12 /// </summary>13 public class Handler1 : IHttpHandler14 {15 public byte[] buffer = null;16 public FileStream filestream = null;17 public void ProcessRequest(HttpContext context)18 {19 20 int length = Convert.ToInt32(context.Request.Files[0].InputStream.Length);21 buffer = new byte[length];22 23 //context.Request.InputStream.Read(buffer, 0, length);24 context.Request.Files[0].InputStream.Read(buffer, 0, length);25 26 string direcotry = System.Environment.CurrentDirectory;27 direcotry = context.Request.Path;28 direcotry = context.Request.MapPath("\\");29 string filename = context.Request.Files[0].FileName;//檔案名稱30 string hzm = filename.Substring(filename.LastIndexOf("."));//尾碼名31 32 filestream = new FileStream(direcotry + DateTime.Now.Ticks.ToString() + hzm, FileMode.Create);33 filestream.Write(buffer, 0, buffer.Length);34 filestream.Flush();35 filestream.Close();36 context.Response.ContentType = "text/plain";37 context.Response.Write("Hello World");38 }39 40 public bool IsReusable41 {42 get43 {44 return false;45 }46 }47 }48 }
JavaScript 之 使用 XMLHttpRequest 上傳檔案