图片上传(方法一:jquery.upload.js)

一、在JSP页面引入jquery.upload.js 文件:

<script type="text/javascript" src="${ctx}/script/jquery.upload.js"></script>

二、JSP页面代码:

<!-- 弹窗  开始  -->
        <div class="dialog_teachermanage" id="addDialog" style="width:923px; display:none" >
              <div class="dialog_title" data-operateType="add"></div>
              <form id="formId" method="post" enctype="multipart/form-data">
                  <div class="dialog_body">
                      <div class="left">

                          <!-- 上传头像  ajax提交  class="hide"  -->
                          <div class="head_photo">
                              <input type="button" id="head_pic_btn" value="点击上传头像" />
                              <img src="${ctx}/static/images/common/head_default.jpg" data-img="head_default.jpg" width="180px" height="210px" id="head_img" />
                          </div>

                          <!-- 上传头像  form提交  -->
                          <!--
                          <div class="tphoto" name="head_img" id="head_img">
                            <input type="file" name="file" id="file" onchange="previewImage(this)" />
                            <div id="preview">
                                <img id="imghead" border="1" width="100px;" heigh="100px;" src=‘${ctx}/static/images/common/head_default.jpg‘>
                            </div>
                          </div>
                           -->

                          <div class="clear" style="height:30px;"></div>
                          <!-- 隐藏的标签查询、输入框 -->
                          <div class="addsign" id="addCourse">
                              <div class="tagdiv">
                                <a class="addtag"><i class=‘iconfont‘></i>添加标签</a>
                                <div class="taginput clearfix">
                                    <input class="form-control" id="tagName" type="text" />
                                    <i class="iconfont ok" id="addtag-ok"></i>
                                    <i class="iconfont cancel" id="addtag-cancel"></i>
                                </div>
                            </div>
                          </div>
                          <ul class="singul labels" name="labels" id="labels"></ul>
                      </div>

                      <div class="right">
                          <input type="hidden" id="id">
                          <div class="right_tinput">
                              <span class="t_span">姓名</span>
                              <input type="text" name="name" id="name" data-rule="required;length[1~30]" data-tip="30字以内"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">头衔</span>
                              <input type="text" name="title" id="title" data-rule="length[0~30]" data-tip="30字以内"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">电话</span>
                              <input type="text" name="phone" id="phone"  data-rule="mobile"  data-rule-mobile="[/^1[3458]\d{9}$/, ‘请检查手机号格式‘]" />
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">邮箱地址</span>
                              <input type="text" name="email" id="email" data-rule="email;length[0~50];"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">讲师类型</span>
                              <select id="trainerTypeId_add"  name="trainerTypeId" placeholder="请选择"/></select>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">专业领域</span>
                              <textarea  cols="46" rows="5" placeholder="限200字" name="proField" id="proField" data-rule="length[0~200]"></textarea>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">简介</span>
                              <textarea cols="46" rows="5" placeholder="限200字" name="intro" id="intro" data-rule="length[0~200]"></textarea>
                          </div>
                      </div>
                  </div>

                  <div class="dialog_bottom">
                      <div class="buttons">
                          <button type="button" id="cancel">取消</button>
                          <button type="submit" >保存</button>
                        </div>
                  </div>
              </form>
          </div>
          <!-- 弹窗  结束  -->

三:JS代码:

<script type="text/javascript" >
    $(function(){

        //点击上传头像
        $("#head_pic_btn").click(function(){
            $.upload({
                url:‘${ctx}/td/trainer/uploadHeadImg.do‘,
                fileName:‘img‘,
                dataType:‘json‘,
                onComplate:function(data){

                    //删除data中<pre>标签
                    var start = data.indexOf(">");
                    if (start != -1) {
                        var end = data.indexOf("<", start + 1);
                        if (end != -1) {
                            data = data.substring(start + 1, end);
                        }
                    }

                    if(data!==‘‘){
                        //$("#head_pic_btn").hide();
                        //$("#head_img").show().attr(‘src‘,"${ctx}/upload/trainer_picture/"+data);

                        $("#head_img").attr("src","${ctx}/upload/trainer_picture/"+data);
                        $("#head_img").attr("data-img",data);

                        /**
                        data=JSON.parse( data.match(/{.+}/)[0] )
                        if( data.result===‘true‘ ){
                            $(‘#head_pic_btn‘).hide();
                            $(‘#head_img‘).show().attr(‘src‘,"${ctx}/upload/trainer_picture/"+data);
                        };
                        alert(data.resultDesc);
                        */
                    };
                }
            });
        });
 });

四、JS提交代码(带预览效果):

//新增修改 验证提交
          $("#formId").validator({
              theme :"simple_bottom",
                valid: function(form){
                    var tname=$(".dialog_title").text();
                     if(tname.indexOf("修改")>=0){
                         //修改保存
                         //SaveEditTeacher();
                         var labels = "";
                      var index = 0;
                      $(".labels").find("li").each(function(){
                          if(index==0){
                              labels += "‘" + $(this).attr("data-id") + "‘";
                          }else{
                              labels += ",‘"+$(this).attr("data-id") + "‘";
                          }
                          index++;
                      });

                      var param={headImg:$("#head_img").attr("data-img"),name:$("#name").val(),title:$("#title").val(),phone:$("#phone").val(),email:$("#email").val(),proField:$("#proField").val(),trainerTypeId:$("#trainerTypeId").val(),address:$("#address").val(),intro:$("#intro").val(),labels:labels };
                      $.ajax({
                            url:"${ctx}/td/trainer/modify.do",
                          type:"get",
                          data:param,
                          success:function(data){
                              if(data.result=="true"){
                                   new AlertWin().initfn({
                                       "tipscon":data.resultDesc,
                                       "showtime":2000
                                   });
                                   $("#formId")[0].reset();
                                   addWin.close();
                               }else{
                                   new AlertWin().initfn({
                                       "tipscon":data.resultDesc,
                                       "showtime":2000
                                   });
                               }
                              //table.load();
                              table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val() } );
                          }
                      });

                     }else{
                         //新增
                         var labels = "";
                      var index = 0;
                      $(".labels").find("li").each(function(){
                          if(index==0){
                              labels += "‘" + $(this).attr("data-id") + "‘";
                          }else{
                              labels += ",‘"+$(this).attr("data-id") + "‘";
                          }
                          index++;
                      });

                      var param={headImg:$("#head_img").attr("data-img"),name:$("#name").val(),title:$("#title").val(),phone:$("#phone").val(),email:$("#email").val(),proField:$("#proField").val(),trainerTypeId:$("#trainerTypeId").val(),address:$("#address").val(),intro:$("#intro").val(),labels:labels };
                      $.ajax({
                            url:"${ctx}/td/trainer/insert.do",
                          type:"get",
                          data:param,
                          success:function(data){
                              if(data.result=="true"){
                                   new AlertWin().initfn({
                                       "tipscon":data.resultDesc,
                                       "showtime":2000
                                   });
                                   $("#formId")[0].reset();
                                   addWin.close();
                               }else{
                                   new AlertWin().initfn({
                                       "tipscon":data.resultDesc,
                                       "showtime":2000
                                   });
                               }
                              //table.load();
                              table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val() } );
                          }
                      });
                     }
                 }
          });

五、Java后台代码:

/**
     *
     * @Title: uploadHeadImg
     * @Description: 上传头像
     * @param @param file
     * @param @param xCoordinate
     * @param @param yCoordinate
     * @param @param width
     * @param @param imgName
     * @param @param height
     * @param @param request
     * @param @param model
     * @param @return
     * @return String
     * @throws
     */
    @RequestMapping(value = "/uploadHeadImg", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String uploadHeadImg(@RequestParam(value = "img", required = false) MultipartFile file,
            @RequestParam(value = "xCoordinate", required = false) Integer xCoordinate,
            @RequestParam(value = "yCoordinate", required = false) Integer yCoordinate,
            @RequestParam(value = "width", required = false) Integer width,
            @RequestParam(value = "imgName", required = false) String imgName,
            @RequestParam(value = "height", required = false) Integer height, HttpServletRequest request, ModelMap model) {

        String result = "";
        EmpMessageRes msg = new EmpMessageRes();

        //获得工程下面upload资源包路径,当然这个包是已经存在的了
        String path = request.getSession().getServletContext().getRealPath("upload/trainer_picture");

        //上传的图片的名称
        String fileName = file.getOriginalFilename();
        String newfileName = UUIDUtil.generateGUID() + fileName.substring(fileName.lastIndexOf(".")).toLowerCase();

        //下面是upload路径盘符的转化
        StringBuffer importPath = new StringBuffer();
        String temp[] = path.split("\\\\");

        for (int i = 0; i < temp.length; i++) {
            importPath.append(temp[i]);
            importPath.append("/");
        }

        importPath.append(newfileName);
        //看是否存在upload包,没有则会新建一个upload包,作为资源上传的路径
        File targetFile = new File(path, newfileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        try { //文件上传
            file.transferTo(targetFile);
            /**
             *利用工具类对图片进行裁剪
             */
            //String name = "D:\\image.jpg";
            if (xCoordinate != null && yCoordinate != null && width != null && height != null) {
                OperateImage o = new OperateImage(xCoordinate, yCoordinate, width, height);
                o.setSrcpath(importPath.toString());
                o.setSubpath(importPath.toString());
                File toCompress = new File(importPath.toString());
                o.cut();
                if (toCompress.length() / 1024 > 50)
                    //将上传的图片进行压缩
                    ImgUtil.createIcon(importPath.toString());
            }
            msg.setResult("true");
            msg.setResultDesc("头像上传成功");
            msg.setImgUrl(newfileName);
            //result = "originalFilename=" + fileName + ";imgUrl=" + msg.getImgUrl() + ";result=" + msg.getResult() + ";resultDesc=" + msg.getResultDesc();

            result = msg.getImgUrl();

        } catch (Exception e) {
            msg.setResult("false");
            msg.setResultDesc("头像上传失败");
            e.printStackTrace();
        }
        if (imgName != null) {
            File later = new File(path, imgName);
            if (later != null)
                later.delete();
        }

        return result;
    }

效果如图:

jquery.upload.js:

var onChooseFile = ‘‘; (function($) {
    var noop = function(){
        return true;
    };
    var frameCount = 0;
    var imgName = ‘‘;
    $.uploadDefault = {
        url: ‘‘,
        fileName: ‘filedata‘,
        dataType: ‘json‘,
        params: {},
        onSend: noop,
        exten: [],
        onComplate: noop
    };

    $.upload = function(options) {
        var opts = $.extend(jQuery.uploadDefault, options);
        if (opts.url == ‘‘) {
            return;
        }

        var canSend = opts.onSend();
        if (!canSend) {
            return;
        }

        var frameName = ‘upload_frame_‘ + (frameCount++);
        var iframe = $(‘<iframe style="position:absolute;height:0;width:0;" name="‘+frameName+‘" />‘);
        var form = $(‘<form method="post" style="display:none;" target="‘+frameName+‘" action="‘+opts.url+‘"  name="form_‘+frameName+‘" enctype="multipart/form-data" />‘);
        // 选中文件, 提交表单(开始上传)
        upFile = function(fileInputDOM) {
            imgName = fileInputDOM.value;
            var extension = imgName.match(/\.[^\.]+$/)[0].toLowerCase(),ontest=false;
            if (options.exten !== undefined) {
                for(var i=0;i<options.exten.length;i++){
                    if( extension===options.exten[i] ){
                        ontest=true;
                    };
                };
                if(!ontest){
                    new Tips({
                        "tipscon": "格式为" + options.exten.join(",") + ",请重新选择!"
                    });
                    opts.ie8&&parElement.append(oldElement)
                    return false;
                };
            };
            form.submit(); 

        };
        var oldElement,parElement,fileInput;
        if(opts.ie8){
            oldElement = $(‘#‘ + opts.fileElementId),parElement=oldElement.parent();
            $(oldElement).appendTo(form);
        }else{
            // form中增加数据域
            var formHtml = ‘<input type="file" name="‘ + opts.fileName + ‘" onchange="upFile(this)">‘;
            for (key in opts.params) {
                formHtml += ‘<input type="hidden" name="‘ + key + ‘" value="‘ + opts.params[key] + ‘">‘;
            }
            form.append(formHtml);
        }

        $(document.body).append(form).append(iframe);
        opts.ie8&&upFile(oldElement[0]);
        // iframe 在提交完成之后
        iframe.load(function() {
            var data = $(this).contents().find(‘body‘).html();
            opts.onComplate(data, imgName);
            if(!data) return false;
            setTimeout(function() {
                opts.ie8&&parElement.append(oldElement)
                iframe.remove();
                form.remove();
            },300);
        });

        // 文件框
        if(!opts.ie8){
            fileInput = $(‘input[type=file][name=‘ + opts.fileName + ‘]‘, form);
            fileInput.click();
        }

    };
})(jQuery);

时间: 2024-10-03 10:22:42

图片上传(方法一:jquery.upload.js)的相关文章

上传系列:jquery.upload.js

最近想做一个上传的总结,把自己用过的上传插件都写一写,哪天用到的时候就不用再一次的翻阅资料,现在页面上用到的上传插件,原理上都差不多,那我也就不再废话了,下面我主要记录一下几个比较常用的,由简到繁,这里我只写代码,其它的就不在啰嗦了: jquery.upload.js ajaxupload.js uploadify SWFUpload jquery.upload.js 这里只写主要的,至于js的引用我就不用说了是吧,自己添加上就行,我就不写了. 前台html代码: 1 <html> 2 <

ASP.NET图片上传(配合jquery.from.js 插件)

前端: js:        function AjaxKouBeiShopEdit() { var options = {                dataType: "json",                success: function (data) {                    alert(data);                                  },                error: function (XMLHttp

ajax图片上传(asp.net +jquery+ashx)

一.建立Default.aspx页面 [csharp] view plain copy <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//E

基于jQuery仿uploadify的HTML5图片上传控件jquery.html5uploader

(function($){ var methods = { init:function(options){ return this.each(function(){ var $this = $(this); var $clone = $this.clone(); var settings = $.extend({ id : $this.attr('id'), button:$this, uploader : '', formData:{}, auto : true, fileTypes : '*

关于vue-element-admin的采坑记录-upload组件图片上传问题

个人博客里部分内容用到了图片上传 那就需要用到vue-element-admin中的upload组件 首先我们需要在需要到图片上传的vue文件里引入upload组件 并使用标签的形式使用该组件 通过v-model绑定image属性 <template> <div class="createPost-container"> <Upload v-model="image"/> </div> </template>

【西祠日志】【07】努力努力,找资料,思考,怎么做asp图片上传

[西祠日志][07]努力努力,找资料,思考,怎么做asp图片上传  (2015.07.23周四) 今天忘了带本子,直接写在书上了笔记,晚点还是夹在本子里: 学了这么久的web应用,一直都没时间去做一点,相对复杂点得应用,比如现在要考虑的图片上传,或者是接下来要加强学习的正则表达式.防SQL注入.验证码的实现.图片水印功能等,这的确是应该作为我学习的第二个阶段,做一点相对复杂一点的应用功能,考虑怎样使自己做的网站更加健壮,今天主要是在找asp资料学习图片上传,考虑了下js实现web富文本编辑器,然

DWZ集成的xhEditor编辑器浏览本地图片上传的设置

有关xhEditor的文件上传配置官方文档链接:http://i.hdu.edu.cn/dcp/dcp/comm/xheditor/demos/demo08.html 一.xhEditor图片上传的配置 DWZ集成的xhEditor默认的配置是默认模式没有如下图上传按钮的,如果需要本地浏览上传,则需相关的配置 这里拿上传图片为例: <textarea class="editor" upimgurl="@Url.Action("xhEditorImgUpload

TP5图片上传

1 /*图片上传*/ 2 public function upload(){ 3 // 获取表单上传文件 例如上传了001.jpg 4 $file = request()->file('file'); 5 // 移动到框架应用根目录/public/uploads/ 目录下 6 $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'); 7 if($info

小程序之图片上传

//调用相册等选择图片,得到图片的相对路劲up_img: function () { var that = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], sourceType: ['album', 'camera'], success: function (res) { var tempFilePaths = res.tempFilePaths; upload(that, tempFilePaths); } }

php 使用 wangeditor3 图片上传

就在最近,公司让我写一个后台,其中用到了富文本编辑器.自从这个富文本的出现 我就慢慢的进入了一个坑,起初不知道用什么编辑器好,看了好多好多,最后选择了.这个 wangeditor3.个人认为这个富文本很干净,还很多功能. 选择了编辑器 我就慢慢的走进了坑的道理,一步一个坎.接下来就是看代码了. 这个是wangeditor,选择一个自己喜欢的版本.我用的是3的 https://github.com/wangfupeng1988/wangEditor/releases 定义一个富文本编辑器 然后富文