前端代码
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js 压缩 上传</title>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<!-- 强制让文档的宽度与设备的宽度保持1:1,并且文档最大的宽度比例是1.0,且不允许用户点击屏幕放大浏览 -->
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width, minimal-ui">
<!-- iphone设备中的safari私有meta标签,它表示:允许全屏模式浏览 -->
<meta name="apple-mobile-web-app-capable" content="yes">
<link href="~/demo/css/style.css" rel="stylesheet" />
</head>
<body>
<div style="width:640px;margin: 0 auto;">
<div class="publish-article-content" id="up1">
<input type="text" id="target" value="/upload/201611/636154171296634724.jpg" style=" width:800px;">
<div class="article-content">
<div id="preview"></div>
<div class="loading">
<div class="loading-bg">
<div class="loading-logo">
<div class="loading-anim"></div>
<div class="loading-tips">上传中</div>
</div>
</div>
</div>
</div>
<div class="footer-btn g-image-upload-box">
<div class="upload-button">
<span class="upload"><i class="upload-img"></i>插入图片</span>
<input class="input-file" id="imgUpload" type="file" multiple="true" name="fileInput" capture="camera" accept="image/*" style="position:absolute;left:0;opacity:0;width:100%;">
</div>
</div>
</div>
</div>
<script src="http://s.0086cc.com/js/jquery-min.js"></script>
<script src="~/demo/js/Uploadzip.js"></script>
<script>
$(function () {
$("#up1").Uploadzip({
imgTar: "imgUpload",
maxSize: 10240,
square: 240, // 压缩后的最大宽度
uploadUrl: "/Home/Upload", //http://s.0086cc.com/upload.php
data: {}, //额外参数
formInputId: "target", //隐场域
uploadSuccess: function (res) {
alert(res.path)
return res.path;
},
//tipsId: "preview"
});
});
</script>
</body>
</html>
后台代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace Js_compression_upload.Controllers
{
public class HomeController : Controller
{
public JsonResult Upload(string field)
{
string imgFilePath = "";
string datafolder = "/upload/" + DateTime.Now.Year.ToString() + ("0" + DateTime.Now.Month.ToString()).Substring(("0" + DateTime.Now.Month.ToString()).Length - 2, 2) + "/"; //文件夹
string txtFileName = DateTime.Now.Ticks.ToString() + ".txt"; //txt文件名
string virtualPath = datafolder + txtFileName; //虚拟路径
string txtFilePath = Server.MapPath(virtualPath); //txt文件保存的地址
if (!Directory.Exists(Path.GetDirectoryName(txtFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(txtFilePath));
}
string[] temp = field.Split(',');
string str = temp[0];
string base64 = temp[1];
string ext = GetExt(str);
if (ext != "")
{
System.IO.File.WriteAllText(txtFilePath, base64, Encoding.ASCII);
imgFilePath = Base64StringToImage(txtFilePath,virtualPath, ext);
}
else
{
goto Complete;
}
Complete:
var res = new JsonResult();
res.Data = new { path = imgFilePath };
return res;
}
private static string GetExt(string str)
{
string ext = "";
if (str.Contains("jpeg"))
{
ext = ".jpg";
}
else if (str.Contains("jpg"))
{
ext = ".jpg";
}
else if (str.Contains("png"))
{
ext = ".png";
}
else if (str.Contains("gif"))
{
ext = ".gif";
}
else if (str.Contains("bmp"))
{
ext = ".bmp";
}
return ext;
}
private string Base64StringToImage(string txtFileName, string virtualPath, string ext)
{
virtualPath = virtualPath.Replace(".txt", ext);
string imgFilePath = txtFileName.Replace(".txt", ext);
FileStream ifs = new FileStream(txtFileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(ifs);
String inputStr = sr.ReadToEnd();
byte[] arr = Convert.FromBase64String(inputStr);
MemoryStream ms = new MemoryStream(arr);
Bitmap bmp = new Bitmap(ms);
switch (ext)
{
case ".jpg":
bmp.Save(imgFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".bmp":
bmp.Save(imgFilePath, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case ".gif":
bmp.Save(imgFilePath, System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".png":
bmp.Save(imgFilePath, System.Drawing.Imaging.ImageFormat.Png);
break;
}
ms.Close();
sr.Close();
ifs.Close();
if (System.IO.File.Exists(txtFileName))
{
System.IO.File.Delete(txtFileName);
}
return virtualPath;
}
}
}
js文件
(function($) {
$.fn.extend({
Uploadzip:function(options) {
var _this = this;
var defaults = {
imgTar:"imgUpload",
maxSize:10240,
square:480,
uploadUrl:"http://s.0086cc.com/upload.php",
data:{},
formInputId:"target",
tipsId:"preview",
uploadSuccess:function(res) {
return res.path;
},
uploadError:function(res) {
console.log(res);
}
};
var _opt = $.extend(defaults, options);
try {
_this.writeHTML(_opt, _this.getValue(_opt.formInputId));
_this.find("#" + _opt.imgTar).on("change", function(e) {
_this.find("#" + _opt.tipsId).parent().append('<div class="loading"><div class="loading-bg"><div class="loading-logo"><div class="loading-anim"></div><div class="loading-tips">上传中</div></div></div></div>');
var file = e.target.files[0];
e.target.value = "";
if ((file.size / 1024).toFixed(2) > _opt.maxSize) {
if (_opt.tipsId) {
_this.find("#" + _opt.tipsId).html("<p>超出最大上传限制" + _opt.maxSize + "KB</p>");
_this.children().find(".loading").hide();
}
console.error("文件太大");
return;
}
var reader = new FileReader();
var imgWidth;
var imgHeight;
reader.readAsDataURL(file);
reader.onload = function(f) {
var image = new Image();
image.src = f.target.result;
imgWidth = image.width;
imgHeight = image.height;
image.width = image.width > _opt.square ? _opt.square : image.width;
var _res = f.target.result.match(/^(data:\s*image\/(\w+);base64,)/);
if (_res == null) {
if (_opt.tipsId) {
_this.find("#" + _opt.tipsId).html("<p>请上传有效的图片文件<p>");
}
console.error("请上传有效的图片文件");
_this.children().find(".loading").hide();
return;
}
if (_opt.tipsId) {
_this.find("#" + _opt.tipsId).html(image);
}
var _type = _res[2];
if (imgWidth > _opt.square && _type != "gif") {
_this.compress(_opt, image, imgWidth, imgHeight, _type);
return;
}
_this.upload(_opt, f.target.result);
return;
};
});
} catch (e) {
console.log(e);
}
},
getValue:function(id) {
var _this = this;
var parentValue = _this.find("#" + id).val();
return parentValue;
},
writeHTML:function(_opt, valueStr) {
var _this = this;
if (valueStr == "" || valueStr == undefined) {
return;
}
if (_opt.tipsId) {
if (_this.find("#" + _opt.tipsId + " img")[0]) {
_this.find("#" + _opt.tipsId + " img").attr("src", valueStr);
} else {
_this.find("#" + _opt.tipsId).append('<img src="' + valueStr + '">');
}
_this.find("#" + _opt.tipsId).append('<i class="close heavy"></i>');
_this.find(".close").click(function(evt) {
_this.reset(_opt);
});
}
},
compress: function (_opt, _img, w, h, t) {
var _this = this;
var canvas = document.createElement("canvas");
var imgScale;
var imgWidth;
var imgHeight;
imgScale = (w / _opt.square).toFixed(8);
imgWidth = _opt.square;
imgHeight = Math.round(h / imgScale);
canvas.width = imgWidth;
canvas.height = imgHeight;
var context = canvas.getContext("2d");
context.drawImage(_img, 0, 0, imgWidth, imgHeight);
var _data = canvas.toDataURL("image/" + t, .8);
_this.upload(_opt, _data);
return;
},
upload:function(_opt, data) {
var _this = this;
$.ajax({
url:_opt.uploadUrl,
type:"post",
data:$.extend(_opt.data, {
field:data
}),
cache:false
}).then(function(res) {
var src = _opt.uploadSuccess(res);
if (src == undefined) {
_opt.uploadError("请上传有效的图片文件");
return;
}
if (_opt.formInputId) {
_this.find("#" + _opt.formInputId).val(src);
}
if (_opt.tipsId) {
if (_this.find("#" + _opt.tipsId + " img")[0]) {
//_this.find("#" + _opt.tipsId + " img").attr("src", src);
} else {
_this.find("#" + _opt.tipsId).append('<img src="' + src + '">');
}
_this.find("#" + _opt.tipsId).append('<i class="close heavy"></i>');
_this.find(".close").click(function(evt) {
_this.reset(_opt);
});
}
_this.children().find(".loading").hide();
});
},
reset:function(_opt) {
var _this = this;
if (_opt.formInputId) {
_this.find("#" + _opt.formInputId).val("");
}
if (_opt.tipsId) {
_this.find("#" + _opt.tipsId).children().remove();
}
}
});
})(jQuery);