私の Web アプリケーションは、(html フォームを使用せずに) 特定の URL に JSON データを投稿することにより、サーバー側 (ASP.NET MVC 3) と対話します。
HttpPostedFileBase
マルチパートフォームを使用せずに、ファイルをサーバーに投稿し、JSON を使用してバインドするにはどうすればよいですか?
ありがとう!
私の Web アプリケーションは、(html フォームを使用せずに) 特定の URL に JSON データを投稿することにより、サーバー側 (ASP.NET MVC 3) と対話します。
HttpPostedFileBase
マルチパートフォームを使用せずに、ファイルをサーバーに投稿し、JSON を使用してバインドするにはどうすればよいですか?
ありがとう!
私はこれを行いましたがHttpPostedFileBase
、MVC アプリからコンテンツを取得するために を使用しませんでした。私は単にJSONを使用しました。
(HTML5の) メソッドを使用FileReader.onload
して、ファイル コンテンツを抽出し、Base64 文字列として MVC コントローラーに直接投稿するだけです。はタグです#upload-button
。<input type=file ...>
var file = $('#upload-button')[0].files[0];
var reader = new FileReader();
reader.onload = (function (f) {
return function (e) {
if (e.target.readyState == FileReader.DONE) {
$.ajax("FileStore/SavePicture", {
data: { content: e.target.result, name: f.name },
type: "post",
contentType: "application/json"
});
}
};
})(file)
そこからConvert.FromBase64String
メソッドを使用して に変換できますbyte[]
。これは、アクション コンテンツがどのように見えるかです。
string base64String = content;
// Get the starting point of the actual content from the base64String.
int start = base64String.IndexOf(",") + 1;
int length = base64String.Length - start;
contentAsString = base64String.Substring(start, length);
byte[] dataAsBytes = Convert.FromBase64String(contentAsString);
これを行う他の方法がいくつかあるかもしれません。
それは可能ですが、クロスブラウザーの問題が発生します。詳細については、こちらを参照してください: How can I upload files asynchronously with jQuery? または単に「ajaxファイルのアップロード」をグーグルで検索します