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

Blazor Server中如何获取<InputFile>选中文件路径?求替代方案

替代解决方案

由于浏览器的安全策略限制,<input type="file">无法获取用户本地文件的真实路径,必须通过文件流传递的方式实现需求:先由前端将文件内容发送到你的API后端,再由后端使用FluentFTP将文件上传到FTP服务器。

1. 前端处理(获取文件并发送到API)

通过HTML文件选择器获取文件,用FormData封装文件后发送到后端接口:

<input type="file" id="fileSelector">
<button onclick="sendFileToAPI()">上传到FTP</button>

<script>
function sendFileToAPI() {
    const fileInput = document.getElementById('fileSelector');
    const selectedFile = fileInput.files[0];
    
    if (!selectedFile) {
        alert('请先选择文件');
        return;
    }

    const formData = new FormData();
    formData.append('uploadedFile', selectedFile);

    fetch('/api/upload-to-ftp', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(result => {
        console.log('FTP上传完成:', result);
        alert('文件上传成功');
    })
    .catch(err => {
        console.error('上传失败:', err);
        alert('文件上传失败');
    });
}
</script>

2. 后端处理(接收文件并上传到FTP)

以ASP.NET Core为例,后端接收前端传递的文件流,再用FluentFTP上传到FTP服务器:

using FluentFTP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api")]
public class FtpUploadController : ControllerBase
{
    [HttpPost("upload-to-ftp")]
    public async Task<IActionResult> UploadToFtp(IFormFile uploadedFile)
    {
        if (uploadedFile == null || uploadedFile.Length == 0)
        {
            return BadRequest("未接收到有效文件");
        }

        // 初始化FTP客户端
        using var ftpClient = new FtpClient("123.123.123.123", "david", "pass123");
        ftpClient.AutoConnect();

        try
        {
            // 直接上传文件流到FTP服务器
            await using var fileStream = uploadedFile.OpenReadStream();
            await ftpClient.UploadFileAsync(
                fileStream, 
                $"/htdocs/{uploadedFile.FileName}", // FTP目标路径+文件名
                FtpRemoteExists.Overwrite // 若文件已存在则覆盖,可根据需求调整
            );

            return Ok(new { Message = "文件成功上传到FTP服务器" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { Message = $"FTP上传失败: {ex.Message}" });
        }
        finally
        {
            ftpClient.Disconnect();
        }
    }
}

关键注意事项

  • 文件大小限制:需在后端配置允许的最大上传文件大小(比如ASP.NET Core中修改Program.cs的MultipartBodyLengthLimit)
  • 文件名冲突:可在后端对文件名进行处理(比如添加时间戳、随机字符串)避免覆盖FTP服务器上的同名文件
  • 异常处理:需添加FTP连接、上传过程中的异常捕获,确保错误信息能返回给前端

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:31:01