js 压缩 上传

前端代码

@{
    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);
要在Mac上下载谷歌浏览器,你可以按照以下步骤进行操作。首先,在Safari浏览器中打开百度并搜索谷歌浏览器官网。接下来,进入官网页面并点击“下载Chrome”按钮,然后选择“接受并安装”来开始下载下载完成后,你可以在浏览器右上角的下载列表图标中找到已下载文件。 如果你觉得用谷歌浏览器下载速度较慢,这可能是因为谷歌浏览器默认使用的是单线程下载。你可以手动开启谷歌浏览器的多线程下载功能来提高下载速度。具体操作方法如下: 1. 打开谷歌浏览器。 2. 在地址栏中输入"chrome://flags"并按下回车键。 3. 在搜索框中输入"并行下载"来快速定位到"并行下载"这个选项。 4. 将"并行下载"的选项设置为"Enabled"。 5. 重新启动谷歌浏览器。 通过开启多线程下载功能,你将能够提高谷歌浏览器下载速度,使其支持同时下载多个文件。 以上就是关于如何在Mac上下载谷歌浏览器以及如何开启谷歌浏览器的多线程下载功能的介绍。如果你还有其他问题,欢迎继续提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [苹果电脑Mac系统如何下载安装谷歌Chrome浏览器](https://blog.csdn.net/weixin_44723106/article/details/104207126)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [谷歌下载东西超慢?开启Chrome多线程下载下载速度提升10倍+](https://blog.csdn.net/weixin_50937908/article/details/108798760)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值