Plupload を使用して、複数の画像を mvc3 Web アプリにアップロードできるようにしています。
ファイルのアップロードは問題ありませんが、AntiForgeryToken を導入すると機能しません。トークンが指定されていないか、無効であるというエラーが表示されます。
Id パラメーターをアクション パラメーターとして受け入れることもできず、常に null を送信します。Request.UrlReferrer プロパティから手動で抽出する必要があります。
私は、pluploadがアップロード内の各ファイルを手動で送信し、独自のフォーム投稿を偽造していると考えています。
私の姿……。
@using (@Html.BeginForm("Upload", "Photo", new { Model.Id }, FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.Id)
<div id="uploader">
<p>You browser doesn't have HTML5, Flash or basic file upload support, so you wont be able to upload any photos - sorry.</p>
</div>
<p id="status"></p>
}
そしてそれをつなぐコード...
$(document).ready(function ()
{
$("#uploader").plupload({
// General settings
runtimes: 'html5,flash,html4',
url: '/Photo/Upload/',
max_file_size: '8mb',
// chunk_size: '1mb',
unique_names: true,
// Resize images on clientside if we can
resize: { width: 400, quality: 100 },
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" }
],
// Flash settings
flash_swf_url: 'Content/plugins/plupload/js/plupload.flash.swf'
});
$("#uploader").bind('Error', function(up, err)
{
$('#status').append("<b>Error: " + err.code + ", Message: " + err.message + (err.file ? ", File: " + err.file.name : "") + "</b>");
});
// Client side form validation
$('uploadForm').submit(function (e)
{
var uploader = $('#uploader').pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0)
{
// Files in queue upload them first
if (uploader.files.length > 0)
{
// When all files are uploaded submit form
uploader.bind('UploadProgress', function ()
{
if (uploader.total.uploaded == uploader.files.length)
$('form').submit();
});
uploader.start();
} else
alert('You must at least upload one file.');
e.preventDefault();
}
});
});
これがそれを受け取るコントローラーアクションです...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(int? id, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var parts = Request.UrlReferrer.AbsolutePath.Split('/');
var theId = parts[parts.Length - 1];
var fileName = theId + "_" + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return Content("Success", "text/plain");
}
ご覧のとおり、id パラメーターを null 可能にする必要があり、これをアクション メソッドで手動で抽出しました。
各フォーム投稿で値が正しく送信されるようにするにはどうすればよいですか?