如何使用普通的旧版本获取ASP.net Web表单(v3.5)发布文件?
我对使用ASP.net FileUpload服务器控件不感兴趣.
谢谢你的建议.
在你的aspx中:
代码背后:
protected void btnUploadClick(object sender, EventArgs e) { HttpPostedFile file = Request.Files["myFile"]; //check file was submitted if (file != null && file.ContentLength > 0) { string fname = Path.GetFileName(file.FileName); file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname))); } }
这是一个不依赖于任何服务器端控件的解决方案,就像OP在问题中描述的那样.
客户端HTML代码:
upload.aspx的Page_Load方法:
if(Request.Files["UploadedFile"] != null) { HttpPostedFile MyFile = Request.Files["UploadedFile"]; //Setting location to upload files string TargetLocation = Server.MapPath("~/Files/"); try { if (MyFile.ContentLength > 0) { //Determining file name. You can format it as you wish. string FileName = MyFile.FileName; //Determining file size. int FileSize = MyFile.ContentLength; //Creating a byte array corresponding to file size. byte[] FileByteArray = new byte[FileSize]; //Posted file is being pushed into byte array. MyFile.InputStream.Read(FileByteArray, 0, FileSize); //Uploading properly formatted file to server. MyFile.SaveAs(TargetLocation + FileName); } } catch(Exception BlueScreen) { //Handle errors } }
你必须设置enctype
的属性form
来multipart/form-data
; 然后您可以使用该HttpRequest.Files
集合访问上传的文件.
将HTML控件与runat服务器属性一起使用
然后在asp.net Codebehind中
FileInput.PostedFile.SaveAs("DestinationPath");
如果您有兴趣,还有一些第三方选项可以显示进度
是的,你可以通过ajax post方法实现这个目标.在服务器端,您可以使用httphandler.所以我们没有按照您的要求使用任何服务器控件.
使用ajax,您还可以显示上传进度.
您必须将文件作为输入流读取.
using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName)) { Byte[] buffer = new Byte[32 * 1024]; int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length); while (read > 0) { fs.Write(buffer, 0, read); read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length); } }
示例代码
function sendFile(file) { debugger; $.ajax({ url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data type: 'POST', xhr: function () { myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { myXhr.upload.addEventListener('progress', progressHandlingFunction, false); } return myXhr; }, success: function (result) { //On success if you want to perform some tasks. }, data: file, cache: false, contentType: false, processData: false }); function progressHandlingFunction(e) { if (e.lengthComputable) { var s = parseInt((e.loaded / e.total) * 100); $("#progress" + currFile).text(s + "%"); $("#progbarWidth" + currFile).width(s + "%"); if (s == 100) { triggerNextFileUpload(); } } } }