[英]Upload file into ASP.NET Core Web API
我们有一个前端 flutter 应用程序,它应该将文件发送到我们的后端(ASP.NET Core Web API)。 问题是:controller应该如何构建? 我相信它应该是一个 POST 方法,但是如何在后端获取这个文件。
PS 所有请求都以 JSON 格式发送至我们的 API。
在 dotnet core controller 你可以使用IFormFile
接口来获取文件,
[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.
}
在 Flutter 中,除了常规文本值之外,您还需要发送 Multipart 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;
}
F# 文件上传需要几个小时才能找出长颈鹿和 HTML 时需要添加一些其他数据 + 拖放
这是代码:
script [ _type "text/javascript"; _src "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ] [];
script [ _type "text/javascript"] [ rawText "
$(function() { $('#uploadForm').submit(function() {
if(!$('form input[type=file]').val()) {
alert('You must select a file!');
return false;
};});}); "];
form [_method "POST"; _action "/upload";
_enctype "multipart/form-data"; _id "uploadForm"; _name "uploadForm"]
h2 [] [ Text "Drop or select file to upload" ];
[ input [ _type "file"; _name "fileName"; _id "file"; ];
input [ _type "text"; _name "Title";];
button [ _type "submit"] [ str "Uppload" ];
];
和
let fileUploadHandler = fun (next : HttpFunc) (ctx : HttpContext) -> task {
return!
(match ctx.Request.HasFormContentType with
| false -> RequestErrors.BAD_REQUEST ("Bad file uppload request")
| true ->
let title = (ctx.Request.Form.Item("Title").ToString()) in
let file = ctx.Request.Form.Files |> Seq.head in
let fileName = file.FileName in
let stream = new MemoryStream() in
file.CopyTo( stream);
let content = Encoding.UTF8.GetString(stream.ToArray()) in
let db_ctx = mssql.GetDataContext() in
let row = db_ctx.Dbo.File.Create(content, fileName, title) in
db_ctx.SubmitUpdates();
htmlView indexView
)
next ctx
}
POST >=> route "/upload" >=> fileUploadHandler;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.