Kre*_*eal 4 c# asp.net asp.net-web-api asp.net-core asp.net-core-webapi
我们有一个前端 flutter 应用程序,它应该将文件发送到我们的后端(ASP.NET Core Web API)。问题是:控制器应该如何构建?我认为它应该是一个POST方法,但是如何在后端获取这个文件。
PS 所有请求都以 JSON 格式发送到我们的 API。
在 dotnet core 控制器中,您可以使用IFormFile
Interface 来获取文件,
[HttpPost("upload-file")]
public async Task<IActionResult> UploadFile([FromQuery] IFormFile file){
if(file.Length > 0){
// Do whatever you want with your file here
// e.g.: upload it to somewhere like Azure blob or AWS S3
}
//TODO: Save file description and image URL etc to database.
}
Run Code Online (Sandbox Code Playgroud)
在 Flutter 中,除了常规文本值之外,您还需要发送多部分 POST 请求来包含具有二进制内容(图像、各种文档等)的文件。
import 'package:http/http.dart' as http;
Future<String> uploadImage(filename, url) async {
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
http.MultipartFile.fromBytes(
'file',
File(filename).readAsBytesSync(),
filename: filename.split("/").last
)
);
var res = await request.send();
return res;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12592 次 |
最近记录: |