導入js
<script src="~/Scripts/ajaxfileupload.js"></script>
cshtml
<style>
#oDiv {
height: 200px;
width: 200px;
border: 1px solid #000;
text-align: center;
margin-bottom: 10px;
}
</style>
<div class="all">
<div id="oDiv">
<img src="" id="showPic" style="height:100%;width:100%" />
</div>
<input type="file" id="oInput" name="file" onchange="upload_cover(this)"/>
<input type="text" id="ImageUrl" name="ImageUrl" placeholder="defaultPath" value="" />
</div>
主要是type="file"的input ,特別注意,它的name="file", 後臺接收寫的樣式一定也要是file
js
function upload_cover(obj) {
//回傳後綴
var filePath = $("input[name='file']").val();
var extStart = filePath.lastIndexOf(".");
var ext = filePath.substring(extStart, filePath.length).toUpperCase();
ajax_upload(obj.id, function (data) { //function(data)是上傳圖片的成功後的回調方法
var isrc = data.relatPath.replace(/\/\//g, '/'); //獲取的圖片的絕對路徑
$('#image').attr('src', basePath + isrc).data('img-src', isrc); //給<input>的src賦值去顯示圖片
}, ext);
}
//具體的上傳圖片方法
function ajax_upload(feid, callback, ext) {
if (image_check(feid)) {
$.ajaxFileUpload({
url: "/Company/UploadImage",
secureuri: false,
fileElementId: feid,
dataType: 'json',
data: {fileType: ext},//增加推送的屬性
type: 'post',
async: true,
secureuri: false,
success:
function (data) {
alert(data.imagePath);
$("#ImageUrl").val(data.imagePath);
$("#showPic").attr("src", data.imagePath);
},
error:
function (data) {
alert(data);
}
});
}
};
function image_check(feid) { //自己添加的文件後綴名的驗證
var img = document.getElementById(feid);
return /.(jpg|png|gif|bmp)$/.test(img.value) ? true : (function () {
modals.info('圖片格式僅支持jpg、png、gif、bmp格式,且區分大小寫。');
return false;
})();
}
controller
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file)
{
//獲取圖片後綴
string fileType = Request.Form["fileType"];
// 時間
string now = DateTime.Now.ToString("yyyyMMddHHmmssffff");
//文件存放的文件路徑
string folder = HttpContext.Server.MapPath("/Content/images/companies/");
// 保存文件
string filePath = Path.Combine(folder, now + fileType);
file.SaveAs(filePath);
//切出相對路徑
string subFilePath = filePath.Substring(filePath.LastIndexOf("\\Content"));
JsonResult json = new JsonResult();
json.ContentType = "text/html";
json.Data = new { imagePath = subFilePath, success = true };
return json;
//return Content(filePath);
}
注意: UploadImage(HttpPostedFileBase file){} 裏面的file 一定要是前臺 name="file"
返回的json不可以直接回傳,需要新建一個JsonResult , 備註json.ContentType = "text/html"; 否則默認是application/json,前臺html無法識別