html
<div id="share-live">
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
HTML内容
</div>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
js
/*
功能:HTML页面保存Base64图片并上传到服务器,返回上传图片信息
实例:
说明:
*/
function htmlToImage (element, callback) {
// var width = element.clientWidth;
// var height = element.clientHeight;
var width = element.offsetWidth;
var height = element.offsetHeight;
var scale = 2;
var canvas = document.createElement("canvas");
// 获取元素相对于视窗的偏移量
var rect = element.getBoundingClientRect();
canvas.width = width * scale;
canvas.height = height * scale;
var context = canvas.getContext("2d");
context.scale(scale, scale);
// 设置context位置, 值为相对于视窗的偏移量的负值, 实现图片复位
context.translate(-rect.left, -rect.top);
var options = {
scale: scale,
canvas: canvas,
// logging: true,
width: width,
height: height,
taintTest: true, //在渲染前测试图片
useCORS: true, //貌似与跨域有关,但和allowTaint不能共存
dpi: window.devicePixelRatio, // window.devicePixelRatio是设备像素比
background: "#fff",
};
html2canvas(element, options).then(function(canvas) {
var dataURL = canvas.toDataURL('image/jpeg', 1.0); //将图片转为base64, 0-1 表示清晰度
var base64String = dataURL.toString().substring(dataURL.indexOf(",") + 1); //截取base64以便上传
var params = new Object();
params.data = base64String;
app.post('uploader/base64', params, function(res) {
if (typeof callback != 'undefined' && callback instanceof Function) {
callback(res);
}
});
});
}
web api
/// <summary>
/// 上传图片(Base64图片,支持多图上传)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[Route("~/Uploader/base64"), HttpPost, AllowAnonymous, CurrentResultAttribute]
public HttpResponseMessage Post([FromBody] JObject obj)
{
ResultData result = new ResultData();
try
{
if (obj["data"] == null || (obj["data"] != null && string.IsNullOrWhiteSpace(obj["data"].ToString())))
{
result.success = false;
result.return_code = HttpStatusCode.OK;
result.return_msg = "没有上传的文件。";
Log.Debug("文件上传API:上传图片(Base64图片,支持多图上传)", result.return_msg);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
BL.IC.Attachment attBL = new BL.IC.Attachment();
List<MD.IC.AttachmentInfo> files = new List<MD.IC.AttachmentInfo>();
string[] reqFiles = obj["data"].ToString().Split('|');
string FilePath = HttpContext.Current.Server.MapPath(WebHelper.GetAppSetting("FilePath")); //文件路径
string UserPath = "1/1000/" + System.DateTime.Now.ToString("yyyyMM") + "/"; //用户路径
string UpLoadPath = Path.Combine(FilePath + UserPath); // 路径合并形成一个上传路径
if (!Directory.Exists(UpLoadPath)) //判断上传路径hi否存在,如果不存在
{
Directory.CreateDirectory(UpLoadPath);
}
for (int i = 0; i < reqFiles.Length; i++)
{
string TempName = Guid.NewGuid().ToString(); //产生一个新的文件别名
string FileName = WebHelper.GenerateRandom(true, true, true, false, 16); //获取到名称
string fileExtension = ".jpg"; //文件的扩展名称
string FileType = "jpg"; //获取文件类型
int FileSize = 0; //获取文件大小
string NewFileName = TempName + fileExtension; //新文件名
string FileSavePath = Path.Combine(UpLoadPath, NewFileName);
byte[] FileByte = Convert.FromBase64String(reqFiles[i]);
// 保存上传文件
File.WriteAllBytes(FileSavePath, FileByte);
// 获取文件大小
using (FileStream fs = new FileStream(FileSavePath, FileMode.Open, FileAccess.Read))
{
FileSize = Convert.ToInt32(fs.Length);
}
// 创建用户文件库记录,同步到数据库
MD.IC.AttachmentInfo entity = new MD.IC.AttachmentInfo();
entity.Userid = 1000; //上传用户ID
entity.Folderid = -1; //目录名
entity.Filename = Path.GetFileNameWithoutExtension(FileName); //文件名
entity.Filesize = FileSize; //文件大小
entity.Filepath = Path.Combine(UserPath, NewFileName); //文件路径
entity.Extend = FileType; //文件后缀名
entity.Createtime = DateTime.Now;
attBL.Insert(entity);
// 添加到返回结果集
files.Add(entity);
}
foreach (MD.IC.AttachmentInfo item in files)
{
item.Filepath = WebHelper.GetHttpDomain() + ConfigurationManager.AppSettings["FilePath"].Replace('\\', '/') + item.Filepath;
}
result.return_code = HttpStatusCode.OK;
result.return_msg = "上传成功";
result.success = true;
result.data = files;
Log.Debug("文件上传API:上传图片(Base64图片,支持多图上传)", result.return_msg + ",JSON:" + JsonHelper.GetJson(files));
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception ex)
{
result.success = false;
result.return_code = HttpStatusCode.OK;
result.return_msg = "接口异常,请稍后再试!";
Log.Debug("文件上传API:上传图片(Base64图片,支持多图上传)", ex.Message);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}