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

如何用JavaScript上传文件至FTP服务器?Angular及C#后端方案咨询

Angular FTP 文件上传解决方案

一、前端 JavaScript 实现方案(仅适合测试,不推荐生产)

浏览器原生 JS 没有内置 FTP 操作 API,你之前尝试的new FtpConnection()属于 Node.js 环境的库(比如ftp包),直接在浏览器中运行会报错。不过有适配浏览器的第三方库可以尝试,比如jsftp(需通过 Webpack/Browserify 打包后在 Angular 中使用):

示例代码

import JSFtp from "jsftp";

// 初始化FTP连接
const ftpClient = new JSFtp({
  host: "你的FTP服务器地址",
  port: 21, // SFTP用22端口
  user: "FTP用户名",
  pass: "FTP密码"
});

// 文件上传逻辑
uploadFileToFtp(file: File) {
  const reader = new FileReader();
  reader.onload = (event) => {
    ftpClient.put(event.target.result, `服务器存储路径/${file.name}`, (err) => {
      if (err) {
        console.error("上传失败:", err);
      } else {
        console.log("上传成功");
        ftpClient.raw.quit(); // 关闭连接
      }
    });
  };
  reader.readAsArrayBuffer(file);
}

⚠️ 关键限制:

  • 前端直接暴露 FTP 账号密码,严重威胁服务器安全
  • 需 FTP 服务器允许跨域请求(大部分公共/企业服务器不会配置)
  • 部分浏览器会因安全策略拦截 FTP 连接

二、后端代理方案(生产环境推荐,以 C# 为例)

这是行业通用的安全方案:前端将文件传给自己的后端 API,由后端完成 FTP 上传,既避免暴露敏感凭证,也解决跨域问题。

C# 后端(ASP.NET Core)示例

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.IO;

[ApiController]
[Route("api/ftp")]
public class FtpUploadController : ControllerBase
{
    [HttpPost("upload")]
    public IActionResult Upload([FromForm] IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("请选择上传文件");

        string ftpServerUrl = "ftp://你的FTP服务器地址/";
        string remoteFilePath = ftpServerUrl + Path.GetFileName(file.FileName);
        
        try
        {
            var ftpRequest = (FtpWebRequest)WebRequest.Create(remoteFilePath);
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpRequest.Credentials = new NetworkCredential("FTP用户名", "FTP密码");

            using (var requestStream = ftpRequest.GetRequestStream())
            using (var fileStream = file.OpenReadStream())
            {
                fileStream.CopyTo(requestStream);
            }

            var response = (FtpWebResponse)ftpRequest.GetResponse();
            response.Close();
            return Ok("文件上传成功");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"上传失败: {ex.Message}");
        }
    }
}

Angular 前端调用示例

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-ftp-upload',
  template: `<input type="file" (change)="handleFileSelect($event)">`
})
export class FtpUploadComponent {
  constructor(private http: HttpClient) {}

  handleFileSelect(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (!file) return;

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

    this.http.post('/api/ftp/upload', formData)
      .subscribe({
        next: res => console.log('上传成功', res),
        error: err => console.error('上传失败', err)
      });
  }
}

总结

  • 前端 JS 实现仅适合本地测试场景,生产环境绝对禁用
  • 后端代理方案(C# 或其他后端语言)是安全、可靠的首选方案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:45:37