项目中使用上传图片的地方非常多,有时间需要客户端先裁剪好图片在上传,这里实现这个功能
图片裁剪插件:cropper.js
前端:layui
后台:asp.net mvc webapi
主要是前端代码,后台就是提供一个上传的api接口
html:
@{
ViewBag.Title = "MKAdmin管理系统";
Layout = "/Views/Shared/_Layout.cshtml";
}
@section Styles {
@Styles.Render(PageCssFilesConfig.FileCropIndex)
}
<div class="layui-input-inline layui-btn-container file-crop-btn">
<button class="layui-btn layui-btn-primary" id="el_fileCropUpload">上传图片</button>
</div>
<div>
<img id="imgFileCropPreview" class="file-crop-img-prerview" src="~/Images/cropDefault.jpg" alt="" />
</div>
@section Scripts {
@Scripts.Render(PageJsFilesConfig.FileCropIndex)
}
js:
//图片裁剪上传
layui.use(['jquery', 'croppers'], function () {
var $ = layui.jquery,
croppers = layui.croppers;
//裁剪上传
croppers.render({
elem: '#el_fileCropUpload'
, mark: 1 / 1 //裁剪比例(宽高比例)
, url: "/home/UploadFile" //
, data: {
uploadfile_ant: 'Crop'
}
, done: function (json) { //上传完毕回调
//alert(JSON.stringify(json));
var data = JSON.parse(json);
console.log(data);
$("#imgFileCropPreview").attr('src', data.data.url);
}
});
});
上传接口:
/// <summary>
/// 上传文件处理
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
public ContentResult UploadFile()
{
HttpFileCollectionBase files = HttpContext.Request.Files;
Result<UploadFileModel> model = new Result<UploadFileModel>();
if (files != null && files.Count > 0)
{
HttpPostedFileBase uploadFileData = files[0];
model.status = false;
if (Request.Form["uploadfile_ant"] == null)
{
model.msg = "请设置参数:ant, 参照web.config中 FileKit->Catalog->Key的值!";
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
string key = Request.Form["uploadfile_ant"].ToString();
var catalogConfig = FileCatalogHelper.Catalog[key];
model.data = new UploadFileModel();
model.data.originalName = uploadFileData.FileName;
string extenName = Path.GetExtension(model.data.originalName);
if (catalogConfig.FileTypeLimit.ToUpper().IndexOf(extenName.ToUpper()) < 0)
{
model.msg = string.Format("请上传文件格式:{0} !", catalogConfig.FileTypeLimit);
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
int fileSizeMax = int.Parse(catalogConfig.FileSize) * 1024 * 1024;
model.data.fileSize = uploadFileData.ContentLength;
if (model.data.fileSize > fileSizeMax)
{
model.msg = string.Format("上传文件必须小于等于 {0}MB", catalogConfig.FileSize);
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
model.data.catalog = $@"/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}";
string filePath = $@"{catalogConfig.TempFile.AbsolutePath}{model.data.catalog.Replace("/", "\\")}";
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
string guid = Guid.NewGuid().ToString("N");
model.data.fileName = string.Format("{0}{1}", guid, extenName);
filePath = Path.Combine(filePath, model.data.fileName);
uploadFileData.SaveAs(filePath);
model.data.url = string.Format("{0}/{1}/{2}", catalogConfig.TempFile.RelativePath
, model.data.catalog, model.data.fileName);
model.status = true;
model.msg = "成功!";
}
else
{
model.msg = "请选择文件";
}
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
前端裁剪图片代码基本都封装好了,所有这里直接调用
效果图