You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dropzone.js移除文件时如何调用ASP.Net Core MVC控制器?

解决Dropzone.js移除文件时同步删除服务器文件的问题

核心思路

Dropzone的removeFile()默认仅处理前端DOM元素,要同步删除服务器文件,需要:

  1. 上传文件时,后端返回文件的唯一标识(如生成的文件名)给前端
  2. 监听Dropzone的removedfile事件,触发时通过AJAX请求后端接口,传入文件标识执行删除

步骤1:修改前端Dropzone配置

在现有init方法中添加上传成功回调和移除文件回调:

<div class="clsbox-1">
    <div class="dropzone clsbox" id="mydropzone"></div>
</div>

<!-- 确保页面包含CSRF令牌(布局页通常已添加,若没有则手动加) -->
@Html.AntiForgeryToken()

<script>
    var accept = ".png";
    Dropzone.autoDiscover = false;

    var myDropzone = new Dropzone("#mydropzone", {
        url: "/test/create",
        acceptedFiles: accept,
        maxFilesize: 0.5,
        uploadMultiple: false,
        createImageThumbnails: false,
        addRemoveLinks: true,
        maxFiles: 1,
        maxfilesexceeded: function(file) {
            this.removeAllFiles();
            this.addFile(file);
        },
        init: function () {
            var drop = this;

            // 上传成功后,保存后端返回的文件名到file对象
            this.on('success', function(file, response) {
                // 后端返回JSON格式:{ "fileName": "xxx.png" }
                file.customData = { fileName: response.fileName };
            });

            // 监听文件移除事件,触发后端删除
            this.on('removedfile', function(file) {
                // 仅当文件已上传成功(有后端返回的文件名)时发起请求
                if (file.customData && file.customData.fileName) {
                    fetch('/test/delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
                        },
                        body: JSON.stringify({ fileName: file.customData.fileName })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (!data.success) alert('服务器文件删除失败');
                    })
                    .catch(err => {
                        console.error('删除请求错误:', err);
                        alert('删除请求出错');
                    });
                }
            });

            // 原有的error事件逻辑保留
            this.on('error', function (file, errorMessage) {
                if (errorMessage.indexOf('Error 404') !== -1) {
                    var errorDisplay = document.querySelectorAll('[data-dz-errormessage]');
                    errorDisplay[errorDisplay.length - 1].innerHTML = 'Error 404: 上传页面未找到';
                }
                if (errorMessage.indexOf('File is too big') !== -1) {
                    alert('文件过大,已移除');
                    drop.removeFile(file);
                }
            });
        }
    });
</script>

步骤2:修改后端控制器(ASP.NET Core MVC)

2.1 更新上传接口,返回文件名

在TestController的Create方法中,上传完成后返回生成的唯一文件名(建议用GUID避免重名):

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.IO;

public class TestController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public TestController(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    [HttpPost]
    public IActionResult Create(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("未选择文件");

        // 定义文件存储目录(示例:wwwroot/uploads)
        var uploadsDir = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
        if (!Directory.Exists(uploadsDir))
            Directory.CreateDirectory(uploadsDir);

        // 生成唯一文件名
        var uniqueFileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
        var filePath = Path.Combine(uploadsDir, uniqueFileName);

        // 保存文件到服务器
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            file.CopyTo(stream);
        }

        // 返回文件名给前端
        return Json(new { fileName = uniqueFileName });
    }
}

2.2 添加删除文件接口

新增Delete方法,接收文件名并删除服务器上的对应文件:

// 定义接收参数的模型
public class DeleteFileRequest
{
    public string FileName { get; set; }
}

[HttpPost]
public IActionResult Delete([FromBody] DeleteFileRequest request)
{
    if (string.IsNullOrEmpty(request.FileName))
        return BadRequest("文件名不能为空");

    var uploadsDir = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
    var filePath = Path.Combine(uploadsDir, request.FileName);

    if (System.IO.File.Exists(filePath))
    {
        System.IO.File.Delete(filePath);
        return Json(new { success = true });
    }

    return Json(new { success = false, message = "文件不存在" });
}

关键注意事项

  • CSRF防护:前端请求必须携带RequestVerificationToken,否则ASP.NET Core会拒绝请求,页面需包含@Html.AntiForgeryToken()
  • 文件唯一性:上传时用GUID生成唯一文件名,避免文件覆盖和删除时误删
  • 错误处理:后端需判断文件是否存在,前端需处理请求失败的情况

内容的提问来源于stack exchange,提问作者Demian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:25:21