如何用TypeScript调用含IFormFile参数的.NET Core文件上传API
正确调用.NET Core文件上传API的TypeScript实现
核心修改要点
- TypeScript中不存在
.NET的IFormFile类型,直接使用浏览器/Node.js原生的File类型即可 - 由于后端API通过
[FromForm]接收数据,必须将请求体包装为FormData,不能直接传递JSON对象 - 发送请求时不要手动设置
Content-Type头,fetch会自动添加正确的multipart/form-data标识及边界参数,避免出现格式错误
修改后的完整代码
类型定义调整
// 替换原有的UploadFileInput接口 export interface UploadFileInput { file: File; // 使用原生File类型替代IFormFile description: string; } // 自定义响应类型(根据你的实际结构调整) export interface CustomResponse<T> { data: T; code?: number; message?: string; }
服务类实现修改
export class MyServiceClient { public async createFile(folderId: string, uploadFileInput: UploadFileInput): Promise<string> { // 更简洁的路径拼接方式 const _path = `http://apiendpoint.com/abc/${folderId}/uploadFile`; // 构建符合后端要求的FormData const formData = new FormData(); // 键名必须和.NET端UploadFileInput的属性名严格匹配(注意大小写) formData.append('File', uploadFileInput.file); formData.append('Description', uploadFileInput.description); const res: CustomResponse<string> = await this.send<string>(_path, 'POST', formData, null); return res.data; } private async send<TOut>(url: string, httpMethod: string, input: any, headers: { [key: string]: any } ): Promise<CustomResponse<TOut>> { const requestUrl = new URL(url); const request: RequestInit = { method: httpMethod, headers: headers || {}, body: input }; // 如果是FormData,删除手动设置的Content-Type,避免边界错误 if (input instanceof FormData && request.headers) { delete request.headers['Content-Type']; } const response = await fetch(requestUrl.href, request); // 处理响应状态,非2xx抛出错误 if (!response.ok) { throw new Error(`上传失败: ${response.status} ${response.statusText}`); } // 解析响应为JSON格式 return response.json() as Promise<CustomResponse<TOut>>; } }
使用示例
// 从浏览器文件选择器获取File对象 const fileSelector = document.getElementById('file-upload') as HTMLInputElement; const selectedFile = fileSelector.files?.[0]; if (selectedFile) { const client = new MyServiceClient(); client.createFile('folder_123', { file: selectedFile, description: '这是一份测试上传文件' }) .then(fileId => console.log('文件上传成功,ID:', fileId)) .catch(err => console.error('上传失败:', err)); }
关键注意事项
- 键名匹配:FormData中append的键名必须和.NET端
UploadFileInput类的属性名完全一致(比如File和Description,.NET默认支持大小写不敏感,但严格匹配更稳妥) - Node.js环境兼容:如果在Node.js中使用,确保版本≥18(原生支持fetch和FormData);低版本需使用
form-data库配合node-fetch - 响应处理:原send方法直接返回response对象,需补充解析JSON的逻辑才能获取
res.data字段
内容的提问来源于stack exchange,提问作者S7H
相关产品推荐
相关产品推荐

