首頁  >  文章  >  web前端  >  JQuery fileupload外掛程式實作檔案上傳功能_jquery

JQuery fileupload外掛程式實作檔案上傳功能_jquery

WBOY
WBOY原創
2016-05-16 15:10:131453瀏覽

道理相通,我簡單分享下在.net MVC下的實裝。

1.製作Model類別

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RCRS.WebApp.LG.EM.Models
{
  //----------------------------------------------------------------
  /// <summary>
  /// Import画面用
  /// </summary>
  //----------------------------------------------------------------
  public class tmp_UploadFile
  {
    /// <summary></summary>
    public HttpPostedFileBase FileName { get; set; }
  }
}

2.實裝controller裡的對應方法,我這個處理邏輯比較複雜,懶得修改了,反正就這個意思

//----------------------------------------------------------------
    /// <summary>
    /// アップロード
    /// </summary>
    /// <returns></returns>
    //----------------------------------------------------------------
    [HttpPost]
    public virtual ActionResult UploadFile()
    {
      HttpPostedFileBase uploadedFile = Request.Files["FileName"];
      string message = "アップロード失敗しました。";
      bool isUploaded = false;
      string path = "";
      string dateTimeNow = DateTime.Now.ToString("yyMMdd-hhmmss");
      string userName = User.Identity.GetUserName();
      string uploadMsg = string.Empty;

      if (uploadedFile != null && uploadedFile.ContentLength != 0)
      {
        string pathForSaving = Server.MapPath("~/App_Data/Uploaded/");
        try
        {
          if (BsnssBihin.IsExcel(uploadedFile.FileName))
          {
            path = System.IO.Path.Combine(pathForSaving, dateTimeNow + "_" + uploadedFile.FileName);
            uploadedFile.SaveAs(path);
            isUploaded = BsnssBihin.UploadBihinChange(path, userName, ref uploadMsg);
            if (isUploaded)
            {
              message = "アップロード成功しました!" + "\n" + uploadMsg;
              Logger.Info("[成功]備品アップロード, " + dateTimeNow + ", " + "[" + userName + "]" + "[" + path + "]" + uploadMsg);
            }
            else
            {
              message = "アップロード失敗しました。" + "\n" + uploadMsg;
              Logger.Info("[失敗]備品アップロード, " + dateTimeNow + ", " + "[" + userName + "]" + "["+path + "]" + uploadMsg);
            }
          }
          else
          {
            message = "ファイルの形式は不正です。";
          }
        }
        catch (Exception ex)
        {
          message = string.Format("失敗しました: {0}", ex.Message);
          Logger.Info("[失敗]備品アップロード: " + ex.Message + dateTimeNow + ", " + "[" + userName + "]" + "[" + path + "]");
        }
      }
      return Json(new { isUploaded = isUploaded, message = message }, "text/html");
    }

3.頁的實裝

@model RCRS.WebApp.LG.EM.Models.tmp_UploadFile
<table align="center" style="margin-bottom:200px">
  <tr>
    <td>
      <div style="width:470px">
        <input type="text" id="tbx-file-path" value="ファイルを選択してください" readonly="readonly" />
      </div>
    </td>
    <td>
      <div style="width: 60px">
        <span class="btn btn-primary fileinput-button">
          <span>選 択</span>
          @Html.TextBoxFor(m => m.FileName, new { id = "file-upload", type = "file", accept = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })
        </span>
      </div>
    </td>
    <td>
      <div style="width:60px">
        <a class="btn btn-primary" href="#" id="hl-start-upload">アップロード</a>
      </div>
    </td>
  </tr>
</table>

<div id="loadingOver" class="loadingOver"></div>
<div id="dvloader" class="dvloader">
  <span class="label label-info" style="align-content:center"> 処理中、少々お待ちください</span><br />
  <br />
  <img id="loadingGif" src="../Content/img/loader.gif" alt="" />
</div>

@section scripts{
  @Scripts.Render("~/bundles/jquery")
  @Scripts.Render("~/bundles/jqueryui")
  @Scripts.Render("~/bundles/jqueryval")
  @Scripts.Render("~/bundles/common")
  @Scripts.Render("~/bundles/fileupload")
  <script type="text/javascript">
    var data_upload;
    $(document).ready(function () {
      'use strict';
      $('#file-upload').fileupload({
        url: '../Bihin/UploadFile',
        dataType: 'json',
        add: function (e, data) {
          data_upload = data;
        },
        done: function (event, data) {
          if (data.result.isUploaded) {
            $("#tbx-file-path").val("ファイルを選択してください");
            data_upload = "";
          }

          $("#dvloader").css("display", "none");
          $("#loadingOver").css("display", "none");

          alert(data.result.message);
        },
        fail: function (event, data) {
          data_upload = "";
          if (data.files[0].error) {

            $("#dvloader").css("display", "none");
            $("#loadingOver").css("display", "none");

            alert(data.files[0].error);
          }
        }
      });
    });

    $("#hl-start-upload").on('click', function () {
      if (data_upload) {
        $("#dvloader").css("display", "block");
        $("#loadingOver").css("display", "block");
        data_upload.submit();
      }
      return false;
    });

    $("#file-upload").on('change', function () {
      $("#tbx-file-path").val(this.files[0].name);
    });

    </script>
}

√,就是這個樣子
還附贈了一個簡易loding的實現
貼出CSS代碼:

.dvloader {
  display:none;
  position:absolute;
  top:40%;
  left:40%;
  width:20%;
  height:20%;
  z-index:1001;
  text-align:center;
  font-size:1.5em;
}

.loadingOver {
  display:none;
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color:#f5f5f5;
  opacity:0.5;
  z-index:1000;
}

這裡,多說一嘴:
關於input 的accept屬性,這裡只想讀入Excel,所以
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel

以上就是本文的全部內容,希望對大家的學習有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn