Reputation: 49
Hi to all i'm a beginner in asp.net fileUploader and i'm using blow code to upload:
The HTML:
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload Selected File(s)" />
JavaScript code:
$("#Button1").click(function (evt) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var options = {};
options.url = "FileUploadHandler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.toString()); };
and the handler code:
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File(s) Uploaded Successfully!");
I have two problems the first it can't find upload file in the root of the web application and second is the page postback is there somebody that help me about solve my problems thank!
Upvotes: 0
Views: 1881
Reputation: 124
I was a little confused with jQuery-File-Upload myself, but after reviewing the plugin documentation I found what is needed for the plugin to work on Windows environment.
PROBLEM 1: FILE SAVING - regarding this issue, make sure that you are saving to a valid and previously created directory, and also that you have WRITE permissions to that directory.
PROBLEM 2: UPLOAD POSTBACK - You must setup your upload script to write the uploaded file, AND return a valid JSON response to the plugin, as defined on the plugin documentation: https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
if (context.Request.Files.Count > 0) {
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++) {
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
}
upload_response = '{"files":[{"name": ' + file.FileName + '","size":' file.FileSize + ',"url":"http:\/\/example.org\/files\/ + file.FileName + ",'
upload_response =+ '"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/ + file.FileName + ","deleteUrl": "http:\/\/example.org\/files\/ + file.FileName + ",'
upload_response =+ '"deleteType": "DELETE"}]}"'
context.Response.ContentType = "application/json";
context.Response.Write( upload_response );
Please note that I also changed the ContentType to "application/json". The syntax of this code may not be complete, but the most important is to output these JSON fields required by the plugin.
Upvotes: 1