问题
I am trying to upload multiple files using the following code.
HTML & JQuery
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="FileUpload.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/jquery-ui-1.8.24.min.js"></script>
<link href="Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload Selected File(s)" />
<div id="progressbar"></div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#progressbar").progressbar({ value: 0 });
$("#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 = "Upload.ashx";
options.type = "POST";
options.data = data;
options.asyn = true;
options.contentType = false;
options.processData = false;
options.dataType = "application/json; charset=utf-8";
options.success = function (data) {
var length = data.length;
for (var i = 0; i < length; i++) {
updateProgress();
}
$("#progressbar").progressbar("value", 100);
};
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
}
}
</script>
</body>
</html>
C# Handler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FileUpload
{
/// <summary>
/// Summary description for Upload
/// </summary>
public class Upload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
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("~/Upload/" + file.FileName);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File(s) Uploaded Successfully!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I have a Jquery UI progress bar which updates based on the percentage completed. I could upload one file. But when I select multiple files to upload, it gives an internal server error. The progress bar is not working at all in either of the cases (uploading one file or multiple file)
Could someone have a look and what is wrong in my code?
Thanks,
UPDATE
I got the multiple files issues sorted. But still couldnt get the progress bar updating.
来源:https://stackoverflow.com/questions/18099826/uploading-images-with-asp-net-generic-handler