1. 程式人生 > 實用技巧 >C#.netmvc單檔案上傳 ajax上傳檔案

C#.netmvc單檔案上傳 ajax上傳檔案

寫到到資料庫的模型

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

namespace WebApplication1.Models
{
    public class UserInfo
    {
        public string Id { get; set; }
    
        public string UserName { get; set; }
   
        
public string Address { get; set; } public HttpPostedFileBase ImgUrl { get; set; } } }

控制器寫法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
using System.IO;

namespace WebApplication1.Controllers
{
    
public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(); } [HttpPost] public string Index(HttpPostedFileBase file) { //判斷檔案是否存在 if (file != null) {
//寫一個檔案儲存的路徑 string imgpath = Server.MapPath(@"\Img\"); //判斷路徑是否存在,不存在則建立 if (!Directory.Exists(imgpath)) { Directory.CreateDirectory(imgpath); } //給檔案再起個名 string ImgName = DateTime.Now.ToString("yyyyMMddHHmmss")+"_"+file.FileName; //把檔案儲存到伺服器上 file.SaveAs(imgpath + ImgName); //返回檔案的位置 return @"\Img\" + ImgName; } return "null"; } } }

前臺頁面寫法

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

<div class="form-group">
    <label for="crowd_file" class="col-sm-2 control-label">上傳檔案</label>
    <div class="col-sm-10">
        <input type="file" accept=".jpg" id="crowd_file">
    </div>
</div>
<div class="form-group">

    <div class="col-sm-10">
        <input type="button" value="上傳" class="submit" id="crowd_file">
    </div>
</div>

<script>
    $('.submit').click(function () {
             var formData = new FormData();
       formData.append("file", $('#crowd_file')[0].files[0]);

        $.ajax({
            url: '/Home/Index',
            dataType: 'json',
            type: 'POST',
            async: false,
            data: formData,
            processData: false, // 使資料不做處理
            contentType: false, // 不要設定Content-Type請求頭
            success: function (data) {
                console.log(data);
                if (data.status == 'ok') {
                    alert('上傳成功!');
                }

            },
            error: function (response) {
                console.log(response);
            }
        });
    })
</script>