效果图:
HTML代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>拖拽上传图片</title>
<script src="/js/jquery/jquery-1.8.2.js" type="text/javascript"></script>
<style type="text/css">
#dropArea {
width: 300px;
height: 100px;
border: 2px dashed #ccc;
text-align: center;
line-height: 100px;
font-size: 16px;
color: #aaa;
margin: 5px auto;
}
#dropArea.dragover {
border-color: #000;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="dropArea" class="manage" style="display: none;">将图片拖放到此处</div>
<asp:HiddenField runat="server" ID="hidFromType" />
</body>
</html>
<script type="text/javascript">
const dropArea = document.getElementById('dropArea');
// 阻止默认行为
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
// 添加拖拽效果
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, () => dropArea.classList.add('dragover'), false);
});
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, () => dropArea.classList.remove('dragover'), false);
});
// 处理文件上传
dropArea.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
if (files.length > 0) {
uploadFile(files[0]);
}
}
// 上传文件到服务器
function uploadFile(file) {
const formData = new FormData();
const fromType = $("#hidFromType").val(); // 获取隐藏字段的值
// 添加数据到 FormData
formData.append('file', file);
formData.append('fromType', fromType);
// 发送请求
fetch('/tools/UploadHandler.ashx', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('上传成功!');
} else {
alert('上传失败:' + data.message);
}
})
.catch(error => {
console.error('上传错误:', error);
alert('上传失败,请稍后再试。');
});
}
</script>
UploadHandler.ashx文件代码如下:
using Aspose.Words.Settings;
using DotNet.FrameWork.Common.Log;
using DotNet.FrameWork.Utils;
using NPOI.OpenXmlFormats.Dml.Diagram;
using OA.crm.crm_customer;
using OABLL;
using OAMODEL;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace OA.tools
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
HttpPostedFile file = context.Request.Files["file"];
// 验证文件是否存在
if (file == null || file.ContentLength == 0)
{
Respond(context, false, "未选择文件或文件为空!");
return;
}
// 验证文件类型
string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif" };
string extension = Path.GetExtension(file.FileName).ToLower();
if (!allowedExtensions.Contains(extension))
{
Respond(context, false, "不支持的文件格式!");
return;
}
// 验证文件大小(例如限制为 5MB)
int maxFileSize = 5 * 1024 * 1024; // 5MB
if (file.ContentLength > maxFileSize)
{
Respond(context, false, "文件过大,最大限制为 5MB!");
return;
}
// 保存文件到服务器
string upLoadPath1 = Class.UpLoad.GetUpLoadPath("0");
string uploadPath = context.Server.MapPath("~" + upLoadPath1);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string fileName = Guid.NewGuid().ToString() + extension;
string filePath = Path.Combine(uploadPath, fileName);
file.SaveAs(filePath);
#region 保存文件到数据库
//根据实际情况编写代码...
//string fromType = context.Request.Form["fromType"] != null ? context.Request.Form["fromType"].ToString() : "";
#endregion
Respond(context, true, "文件上传成功!", $"{upLoadPath1}{fileName}", file.FileName);
}
catch (Exception ex)
{
Respond(context, false, $"上传失败:{ex.Message}");
}
}
private void Respond(HttpContext context, bool success, string message, string filePath = null, string fileName = null)
{
context.Response.ContentType = "application/json";
var response = new
{
success,
message,
filePath,
fileName
};
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(response));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}