我们有一个前端Flutter应用程序,需要将文件发送到我们的后端(ASP.NET Core Web API)。
问题是:如何构建控制器?我相信它应该是POST方法,但是如何在后端获取这个文件。
备注:所有请求以JSON格式发送到我们的API。
备注:所有请求以JSON格式发送到我们的API。
在dotnet core控制器中,您可以使用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.
}
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# 文件花了几个小时才弄清楚 giraffe 和 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;