在Angular / Nest / GraphQL中无法进行文件上传的问题通常是由于请求头或服务器配置引起的。以下是可能的解决方法:
import { HttpClient, HttpHeaders } from '@angular/common/http';
// ...
const formData = new FormData();
formData.append('file', file);
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
this.http.post(url, formData, { headers }).subscribe(response => {
// handle response
}, error => {
// handle error
});
@nestjs/platform-express
中的FileInterceptor
中间件来处理文件上传。确保在使用FileInterceptor
中间件时将limits
选项设置为适当的大小限制,并使用fileFilter
选项来验证文件类型。import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
// ...
@Controller('files')
export class FilesController {
@Post('upload')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 1024 * 1024 } }))
async uploadFile(@UploadedFile() file) {
// handle file upload
}
}
请注意,上述示例中的代码是基于Angular 12和Nest 8的版本。根据你的版本可能会有所不同,但整体概念是相同的。
如果以上解决方法无法解决问题,你可以提供更多的代码示例和错误信息,以便更好地帮助你解决问题。