0

MVC 4 プロジェクトとして CMS を構築していますが、機能の 1 つは写真をアップロードすることです。ユーザーがハード ドライブから写真を選択すると、コントローラーの UploadFile メソッドに対する ajax 要求がトリガーされます。これにより、写真がサーバー上の仮想フォルダーにコピーされます。問題は、ブラウザがファイルを保存してサーバーに送信する場所と、コントローラで何をすべきかをよく理解していないことです。

これはこれまでの私のコードです-

景色:

<input id="cng_pic_btn" type="file" name="file" accept="image/*" /></td>

サーバーへの呼び出しを行う JavaScript:

$('#cng_pic_btn').live('change', function () {

    custom_url = "/SideBar/UploadFile";
    return_msg = "file uploaded";

    var file_path = $('#cng_pic_btn').attr("value");
    alert(file_path);
    sendInfo = {
        upload_from: file_path
    }

    CreataAjaxRequest(custom_url, sendInfo, return_msg);

})

コントローラー方式:

    [HttpPost]
    public void UploadFile(string upload_from)
    {
            string path = @"D:\Temp\";

            HttpPostedFileBase photo = Request.Files[upload_from];

            photo.SaveAs(path + photo.FileName);
    }

ajax リクエストを送信します。

function CreataAjaxRequest(custom_url, sendInfo, return_msg) {

    $.ajax({ type: "POST", url: custom_url, data: sendInfo })
                .success(function (html) {
                    $(".query-result").replaceWith(html);

                })

}
4

1 に答える 1

1

メソッドを示していませんCreataAjaxRequestが、AJAX を使用してファイルをアップロードする場合は、いくつかのオプションがあります。

  • クライアント ブラウザがサポートしHTML 5 File APIている場合は、XmlHttpRequest2 オブジェクトを使用できます。
  • クライアント ブラウザーがファイル API (Internet Explorer など) をサポートしていない場合、ファイル アップロード プラグインを使用するUploadifyFine Uploader、そのような種類のレガシー ブラウザー用の非表示の iframe や Flash ムービーなどの手法を使用できます。

HTML 5 File API を使用してファイルをアップロードする方法の例を次に示します。

function CreataAjaxRequest(custom_url, sendInfo, return_msg) {
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    xhr.open('POST', custom_url, true);
    var file = document.getElementById('cng_pic_btn').files[0];;
    fd.append('myFile', file);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            $('.query-result').replaceWith(xhr.responseText);
        }
    };
    xhr.send(fd);
}

次に、サーバー上で:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase myFile)
{
    var path = string path = @"D:\Temp\";
    myFile.SaveAs(Path.Combine(path, myFile.FileName));

    return PartialView();
}

PartialView また、AJAX コールバックでメソッドを使用する場合は、コントローラー アクションが を返す必要があることにも注意してください$('.query-result').replaceWith(xhr.responseText);。それ以外の場合は、何に置き換えますか?

于 2013-03-10T12:29:09.853 に答える