IT業界のすみっこ暮らし

ふと気がついたときの記録



string文字列のxmlパーシング

XML

<?xml version="1.0" encoding="UTF-8"?>
<Data>
    <CustomerName>名前</CustomerName>
    <OrderList>
        <OrderData>
            <OrderName>注文1<OrderName>
        </OrderData>
        <OrderData>
            <OrderName>注文2<OrderName>
        </OrderData>
    </OrderList>
</Data>

単品項目の値を取得

using System.Xml;


string xml = パーシングするXMLのstring文字列;

XmlDocument xml = new XmlDocument();
xml.LoadXml(xml);

var customerName = node.SelectNodes("CustomerName")[0].InnerText;

一覧項目の値を取得

using System.Xml;


string xml = パーシングするXMLのstring文字列;

XmlDocument xml = new XmlDocument();
xml.LoadXml(xml);

XmlNodeList nodeList = xml.SelectNodes("/Data/OrderList/OrderData");

if (nodeList.Count > 0)
{
    foreach (XmlNode node in nodeList)
    {
        orderName = node.SelectNodes("OrderName")[0].InnerText;
    }
}

ASP.NET MVCでファイルアップロード

1、MVCでファイルアップロード

Upload.cshtml

@using (Html.BeginForm("Upload", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <input type="file" name="uploadFile" />
    <button type="submit">登録</button>
}

HomeController

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(FormCollection formCollection)
{
    var fileName = string.Empty;

    if (Request != null)
    {
        HttpPostedFileBase file = Request.Files["uploadFile"];
        
        // 処理
    }
    return View();
}

※F5押下などで画面をリフレッシュする度アクションが呼び出されるので2の方法をお勧め。

2、MVCとAjaxでファイルアップロード

Upload.cshtml

<div>
    @using (Html.BeginForm("Upload", "Home", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <button type="button" onclick="$('#inputFile').click();">ファイル選択</button>
        <input id="inputFile" type="file" style="display:none;" />
        <div id="uploadFile">選択されていません</div>
        <button id="btnUpload" type="button">ファイルアップロード</button>
    }
</div>
<script src="~/xxxx/Upload.js"></script>
<script type="text/javascript">
   upload.init();
</script>

Upload.js

var upload = {
    uploadFile: null,
    init: function () {
        this.buttons.init();
    },
    buttons: {
        init: function () {
            this.btnInputFile.change();
            this.btnUpload.click();
        },
        btnInputFile: {
            change: function () {
                $('#inputFile').change(function (e) {
                    $.each(e.target.files, function () {
                        page.importFile(this);
                    });
                    return false;
                });
            }
        },
        btnUpload: {
            click: function () {
                $('#btnUpload').click(function () {
                    if (page.uploadFile == null) {
                        alert('ファイルを選択してください。');
                        return;
                    }

                    var $form = $(this).closest('form')
                    var formData = new FormData($form.get(0));
                    formData.append("file", page.uploadFile);
                    
                    $.ajax({
                        type: 'POST',
                        url: '/Home/Upload',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (data) {
                            if (data.IsSuccess) {
                                alert('アップロード成功!');
                            } else {
                                alert('アップロード失敗!');
                            }
                            page.importFileReset();
                        },
                        error: function (data) {
                            alert('システムエラー!');
                            page.importFileReset();
                        }
                    });
                    
                    return false;
                });
            }
        }
    },
    importFile: function (file) {
        $('#uploadFile').replaceWith('<div id="uploadFile">' + file.name + '</div>');
        page.uploadFile = file;
    },
    importFileReset: function () {
        $('#uploadFile').replaceWith('<div id="uploadFile">選択されていません</div>');
        page.uploadFile = null;
    }
}

HomeController

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase file)
{
    var fileName = string.Empty;
    var model = new JsonResultModel();
    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
    {
        fileName = file.FileName;
        string fileContentType = file.ContentType;
        byte[] fileBytes = new byte[file.ContentLength];
        var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));

        // 処理      
    }

    return Json(model, JsonRequestBehavior.AllowGet);
}

追記。複数ファイルをアップロードする場合(2017.04.19)

単数から複数に設定するだけ。

Upload.cshtml

  • 単数
<input id="inputFile" type="file" style="display:none;" />
  • 複数
<input id="inputFile" type="file" multiple style="display:none;" />

Upload.js

  • 単数
uploadFile: null
----------------------
formData.append("file", page.uploadFile);
----------------------
page.uploadFile = file;
  • 複数
uploadFiles: []
----------------------
$.each(page.uploadFiles, function () {
    formData.append("files", this);
});
----------------------
page.uploadFiles.push(file);

HomeController

  • 単数
public ActionResult Upload(HttpPostedFileBase file)
  • 複数
public ActionResult Upload(HttpPostedFileBase[] files)

参考サイト

1、MVCでファイルアップロード

www.c-sharpcorner.com

2、MVCとAjaxでファイルアップロード stackoverflow.com

blog.regrex.jp

3、その他、formデータに要素追加参考

stackoverflow.com





プライバシーポリシー