1.视图页面
<div>
<label type="button" class="btn">
<span>选择图片</span>
<input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="" name="img">
</label>
<img id='myImg' src="" alt="">
</div>
2.js预览
document.querySelector('#uploaderInput').onchange = function () {
var read = new FileReader()
read.readAsDataURL(this.files[0])
read.onload = function () {
url = read.result
document.querySelector('#myImg').src = url
}
}
var imgName = "";
function getImgName(data) {
imgName = data;
}
3.ajax获取后台地址
function uploadImag(file) {
var formData = new FormData();
formData.append('file', file);
$.ajax({
//rver script to process data
dataType: "json",
url: '/EI_ExpertInfo/UpLoadFile',
type: 'POST',
success: function (data) {
//success event
//document.querySelector("#myIma") = data;
getImgName(data.datas[0].filename);
console.log(data.datas[0].filename);
},
error: function (e) {
//errorHandler
},
///Form data
data: formData,
///Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
}
4.后台更改图片名称地址和图片检查
private readonly IHostingEnvironment _env;
public EI_ExpertInfoController(IHostingEnvironment env)
{
_env = env;
}
[HttpPost]
public JsonResult UpLoadFile()
{
var files = Request.Form.Files;
var now = DateTime.Now;
var webRootPath = _env.WebRootPath;
var filePath = @"/Uploads/Images/";
if (!Directory.Exists(webRootPath + filePath))
{
try
{
Directory.CreateDirectory(webRootPath + filePath);
}
catch
{
return Json(new { code = 0, msg = "无法创建服务端{@wwwroot/Uploads/Images/}目录,请确认是否有操作权限!" });
}
}
try
{
if (files.Count() > 0)
{
List<UploadImageModel> list = new List<UploadImageModel>();
foreach (var uploadfile in files)
{
//文件后缀
var fileExtension = Path.GetExtension(uploadfile.FileName);
long fileSize = uploadfile.Length; //获得文件大小,以字节为单位
var strDateTime = DateTime.Now.ToString("yyyyMMddhhmm"); //取得时间字符串
var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
var saveName = strDateTime + strRan + fileExtension;
//检查文件扩展名是否合法
if (!CheckFileExt(fileExtension))
{
return Json(new { code = 0, msg = "不允许上传" + fileExtension + "类型的文件", result = "no", message = "不允许上传" + fileExtension + "类型的文件" });
}
//检查文件大小是否合法
if (!CheckFileSize(fileSize))
{
return Json(new { code = 0, msg = "文件超过限制的大小", result = "no", message = "文件超过限制的大小" });
}
using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
{
uploadfile.CopyTo(fs);
fs.Flush();
}
list.Add(new UploadImageModel
{
filename = "../../Uploads/Images/"+saveName,
url = $"{Request.Scheme}://{Apache Tomcat/9.0.35}" + filePath.Replace("", "/") + saveName,
});
}
return Json(new { code = 1, msg = "上传成功", datas = list, result = "ok", message = "上传成功" });
}
return Json(new { code = 0, msg = "上传失败", result = "no", message = "上传失败" });
}
catch (Exception ex)
{
return Json(new { code = 0, msg = ex.Message, result = "no", message = "上传失败" });
}
}
/// <summary>
/// 检查是否为合法的上传文件
/// </summary>
private bool CheckFileExt(string _fileExt)
{
//检查危险文件
string[] excExt = { "asp", "aspx", "ashx", "asa", "asmx", "asax", "php", "jsp", "htm", "html" };
for (int i = 0; i < excExt.Length; i++)
{
if (excExt[i].ToLower() == _fileExt.ToLower())
{
return false;
}
}
//检查合法文件
string[] allowExt = (".gif,.jpg,.png,.bmp,.rar,.zip,.doc,.xls,.txt,.jpeg,.png").Split(',');
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i].ToLower() == _fileExt.ToLower())
{
return true;
}
}
return false;
}
private bool CheckFileSize(long _fileSize)
{
if (_fileSize > 1024 * 1024 * 10)
{
return false;
}
return true;
}
#endregion