uploadhandler.ashx.cs
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string dirFullPath = HttpContext.Current.Server.MapPath("~/Uploader/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/Uploader/") + str_image;
file.SaveAs(pathToSave_100);
}
}
// database record update logic here ()
context.Response.Write(str_image);
}
catch (Exception ac)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
JSCODE
/Image Upload code
function sendFile(file) {
var formData = new FormData();
formData.append('file', $('#f_UploadImage')[0].files[0]);
$.ajax({
url: 'UploadHandler.ashx',
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(result) {
if (result != 'error') {
var my_path = "Uploader/" + result;
$("#myUploadedImg").attr("src", my_path);
}
},
error: function(err) {
alert(err.statusText);
}
});
}
function callImgUploader() {
var _URL = window.URL || window.webkitURL;
$("#f_UploadImage").on('change', function() {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
sendFile(file);
};
img.onerror = function() {
alert("Not a valid file:" + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
}
注意:我的aspx页面是不同的文件夹, Image Folder and UploadHandler.ashx.cs
是路由文件夹吗?
运行ajax request
后,每次给出Not-Found
错误如何修复。
谢谢。
您没有提及您使用的上传控件,我假设它是服务器端,您需要如下访问它
更改
$('#f_UploadImage')
to
$('#<%= f_UploadImage.ClientID %>')
您说
我的aspx页面是不同的文件夹和图像文件夹,uploadhandler.ashx.cs
您必须更改
url: 'UploadHandler.ashx',
to
url: '/UploadHandler.ashx',
否则,它将尝试在与Ajax页面同一文件夹中搜索UploadHandler.ashx
并给出404。
我认为问题是contentType try
contentType:'Multipart/form-data',
感谢您的所有有价值的反馈,
现在我的问题已经解决,UploadHandler.ashx
设置中的问题
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UploadHandler.ashx.cs" Inherits="Customer.UploadHandler" %>
继承值与我的UploadHandler.ashx.cs
名称空间不匹配,该名称空间已解决。
谢谢大家。