轉載自:https://www.cnblogs.com/wyy1234/p/9455154.html
layui中提供了非常簡單的文件上傳組件,這里寫了一個上傳圖片的栗子,上傳成功后返回圖片在服務器的路徑,並設置為頁面中img的src屬性。因為上傳十分簡單,沒什么可說的,就直接上代碼了。
html代碼
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon"></i>選擇圖片
</button>
<button type="button" class="layui-btn" id="btnUpload">開始上傳</button>
<img id="myPic" src="" width="500" />
JS代碼
<script>
layui.use(['upload', 'jquery'], function () {
var upload = layui.upload;
var $ = layui.$;
//執行實例
var uploadInst = upload.render({
elem: '#test1' //綁定元素
, url: '/Home/UploadImg' //上傳接口
//*********************傳輸限制
, size: 100 //傳輸大小100k
, exts: 'jpg|png|gif|' //可傳輸文件的后綴
, accept: 'file' //video audio images
//****************傳輸操作相關設置
, data: { Parm1: "hello", Parm2: "world" } //額外傳輸的參數
, headers{token:'sasasasa'} //額外添加的請求頭
, auto: false //自動上傳,默認是打開的
, bindAction: '#btnUpload' //auto為false時,點擊觸發上傳
, multiple: false //多文件上傳
//, number: 100 //multiple:true時有效
, done: function (res) { //傳輸完成的回調
console.log(res.IsSuccess)
console.log(res.Msg)
$('#myPic').attr("src", res.Src);
}
, error: function () { //傳輸失敗的回調
//請求異常回調
}
});
});
</script>
后台接口(使用.net mvc)
public ActionResult UploadImg(string Parm1,string Parm2)
{
if (Request.Files.Count>0)
{
//p1,p2沒什么用,只是為了證明前端中額外參數data{parm1,parm2}成功傳到后台了
string p1 = Parm1;
string p2 = Parm2;
//獲取后綴名
string ext = Path.GetExtension(Request.Files[0].FileName);
//獲取/upload/文件夾的物理路徑
string mapPath = Server.MapPath(Request.ApplicationPath);
//通過上傳時間來創建文件夾,每天的放在一個文件夾中
string dir = mapPath + "upload/"+DateTime.Now.ToString("yyyy-MM-dd");
DirectoryInfo dirInfo = Directory.CreateDirectory(dir);
//在服務器存儲文件,文件名為一個GUID
string fullPath = dir + "/" + Guid.NewGuid().ToString()+ ext;
Request.Files[0].SaveAs(fullPath);
//獲取圖片的相對路徑
string imgSrc = fullPath.Replace(mapPath, "/");
return Json(new { IsSuccess = 1, Msg = "上傳成功", Src = imgSrc });
}
else
{
return Json(new { IsSuccess = 0, Msg = "上傳失敗", Src = "" });
}
}

