File upload with JQuery and ASP.NET Generic Handler - Is it possible?
I am trying to solve a small issue. I have built an entire web ASP.NET application using mostly client side (JQuery/JavaScript) code. I use generic handlers to do some lazy loading of data, as well as for auto-completes and the likes.
One of the requirements is that one page needs to be able to upload a file, as well as display meta information about the uploadead files.
I as wondering if there is a way to upload a file entirely out of JQuery/JavaScript. I researched a whole ot of plugins but they all rely on having a php backend.
My thought was to create a post:
$(function(){
$('#submit').live('click', function(event){
$.post('/SomeOtherHandler.ashx', //can be '/someotherpage.aspx'
{
filena开发者_StackOverflow中文版me: $('#fileUpload').val(),
timestamp: (new Date()).toString()
}, function(data){
//do something if the post is successful.
});
});
});
Would that work? I know that if you include the json object { filename: value, timestamp: value }
it will show up in the HttpContext.Request.Params
collection where I can read it without problems.
The problem is however that I don't know how this will work since the FileUpload html control only stores the file name in its value. Therefore I would be sending a string to my server with the filename, not an array of bytes.
Any thoughts on this would be greatly appreciated!
I'm using the uploadify plugin (http://www.uploadify.com/) - as Jeremy said, it's not in javascript - It's not possible. It's in flash. It's very easy to install.
$('#file_upload').uploadify({
'uploader' : '/uploadify/uploadify.swf',
'script' : '/uploadify/uploadify.ashx',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/uploads',
'auto' : true,
'fileExt': '*.xls;*.xlsx;*.csv',
'buttonText': 'Select your file',
'onError' : function (event,ID,fileObj,errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
},
'onComplete' : function(event, ID, fileObj, response, data)
{
var obj = jQuery.parseJSON(response);
if (obj.error != "" & obj.errror != null)
{
lblTable.html("error : " + obj.error);
}
else
{
lblTable.html(obj.table);
lblEditData.show();
lblTable.hide();
}
}
});
And on the uploadify.ashx :
public class uploadify : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpPostedFile file = context.Request.Files["Filedata"];
//Check extension
string extension = "";
try
{
extension = file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
if (extension != "xls" & extension != "xlsx" & extension != "csv") throw new Exception("Error of the extension");
}
catch
{
context.Response.Write("{\"error\",\"Error with the extension of the file\"");
}
string linkFile = System.Web.HttpContext.Current.Server.MapPath("~") + "uploads" + "\\" + DateTime.Now.ToString("yyMMddHHmm") + APIReportPro.DocumentPDF.RandomString(4) + "." + extension;
file.SaveAs(linkFile);
...etc...
This is the nicest solution I found for asp.net
You have what boils down to three options when you are uploading files to a server. You can use native html file-upload features, Flash or Java. Javascript cannot upload a file to a server, it can only decorate the built in html functionality. With that said I can only assume you are attempting to mimic ajax like uploading functionality. If that is so there is a way to upload files using an iframe which will look like you are using ajax.
You will be creating a form
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.aspx">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
This form uses the iframe to post the file, which will cause the main page to never refresh. You can hook up your jquery to process the response the iframe returns and handle user information.
If this is not the part of the equation you were looking for please feel free to comment and clarify what it is you are looking to accomplish.
If you can dictate which browsers your app is accessed through (e.g. it's an internal business app), it's worth checking out the new File API which is part of the "HTML5" stack of technologies that are beginning to show up in the latest browsers. This gives you direct access to files via clientside Javascript without the need to post the file to the server first.
If your app is public-facing then you can still use the File API, but you will need to check for support for it in your code and apply some kind of fallback mechanism (such as Uploadify) for those with older browsers.
You can read more about the File API here and here amongst other places.
I'm pretty sure it's not possible; if it is then it's a big security hole - Javascript should not be able to get bytes from the user's hard drive.
So you're stuck using the native input type=file or using pre-existing desktop bytes, like Flash. Several popular uploaders use this method...my favorite is Uploadify. Take a look at that, and see if that doesn't suit your needs.
HTH.
I have implemented an ASP.NET Handler for uploading file using Valums ajax Upload control. You can check solution here. You can also upload large file. This handler supports IE, FF and Chrome browser. You can also drag drop multiple files from FF and Chrome (HTML 5)
http://ciintelligence.blogspot.com/2011/05/aspnet-server-side-handler-for-valums.html
Using jquery you can do something like:
<input type="file" name="file" id="file1" runat="server" />
$("#<%=file1.ClientID%>").change(function () {
//Do stuff
$(this).upload('youHandler.ashx', function (res) {
//do stuff on success
}
}
Now on yourHandler.ashx you can do something like that:
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
var fileCount = context.Request.Files.Count;
var fileStram = var file = context.Request.Files[0].InputStream;
//Do whatever you want
}
}
精彩评论