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

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

二、JSP页面代码:

  1. <!-- 弹窗 开始 -->
  2. <div class="dialog_teachermanage" id="addDialog" style="width:923px; display:none" >
  3. <div class="dialog_title" data-operateType="add"></div>
  4. <form id="formId" method="post" enctype="multipart/form-data">
  5. <div class="dialog_body">
  6. <div class="left">
  7.  
  8. <!-- 上传头像 ajax提交 class="hide" -->
  9. <div class="head_photo">
  10. <input type="button" id="head_pic_btn" value="点击上传头像" />
  11. <img src="${ctx}/static/images/common/head_default.jpg" data-img="head_default.jpg" width="180px" height="210px" id="head_img" />
  12. </div>
  13.  
  14. <!-- 上传头像 form提交 -->
  15. <!--
  16. <div class="tphoto" name="head_img" id="head_img">
  17. <input type="file" name="file" id="file" onchange="previewImage(this)" />
  18. <div id="preview">
  19. <img id="imghead" border="1" width="100px;" heigh="100px;" src='${ctx}/static/images/common/head_default.jpg'>
  20. </div>
  21. </div>
  22. -->
  23.  
  24. <div class="clear" style="height:30px;"></div>
  25. <!-- 隐藏的标签查询、输入框 -->
  26. <div class="addsign" id="addCourse">
  27. <div class="tagdiv">
  28. <a class="addtag"><i class='iconfont'></i>添加标签</a>
  29. <div class="taginput clearfix">
  30. <input class="form-control" id="tagName" type="text" />
  31. <i class="iconfont ok" id="addtag-ok"></i>
  32. <i class="iconfont cancel" id="addtag-cancel"></i>
  33. </div>
  34. </div>
  35. </div>
  36. <ul class="singul labels" name="labels" id="labels"></ul>
  37. </div>
  38.  
  39. <div class="right">
  40. <input type="hidden" id="id">
  41. <div class="right_tinput">
  42. <span class="t_span">姓名</span>
  43. <input type="text" name="name" id="name" data-rule="required;length[1~30]" data-tip="30字以内"/>
  44. </div>
  45. <div class="right_tinput">
  46. <span class="t_span">头衔</span>
  47. <input type="text" name="title" id="title" data-rule="length[0~30]" data-tip="30字以内"/>
  48. </div>
  49. <div class="right_tinput">
  50. <span class="t_span">电话</span>
  51. <input type="text" name="phone" id="phone" data-rule="mobile" data-rule-mobile="[/^1[3458]\d{9}$/, '请检查手机号格式']" />
  52. </div>
  53. <div class="right_tinput">
  54. <span class="t_span">邮箱地址</span>
  55. <input type="text" name="email" id="email" data-rule="email;length[0~50];"/>
  56. </div>
  57. <div class="right_tinput">
  58. <span class="t_span">讲师类型</span>
  59. <select id="trainerTypeId_add" name="trainerTypeId" placeholder="请选择"/></select>
  60. </div>
  61. <div class="right_tinput">
  62. <span class="t_span">专业领域</span>
  63. <textarea cols="46" rows="5" placeholder="限200字" name="proField" id="proField" data-rule="length[0~200]"></textarea>
  64. </div>
  65. <div class="right_tinput">
  66. <span class="t_span">简介</span>
  67. <textarea cols="46" rows="5" placeholder="限200字" name="intro" id="intro" data-rule="length[0~200]"></textarea>
  68. </div>
  69. </div>
  70. </div>
  71.  
  72. <div class="dialog_bottom">
  73. <div class="buttons">
  74. <button type="button" id="cancel">取消</button>
  75. <button type="submit" >保存</button>
  76. </div>
  77. </div>
  78. </form>
  79. </div>
  80. <!-- 弹窗 结束 -->

三:JS代码:

  1. <script type="text/javascript" >
  2. $(function(){
  3.  
  4. //点击上传头像
  5. $("#head_pic_btn").click(function(){
  6. $.upload({
  7. url:'${ctx}/td/trainer/uploadHeadImg.do',
  8. fileName:'img',
  9. dataType:'json',
  10. onComplate:function(data){
  11.  
  12. //删除data中<pre>标签
  13. var start = data.indexOf(">");
  14. if (start != -1) {
  15. var end = data.indexOf("<", start + 1);
  16. if (end != -1) {
  17. data = data.substring(start + 1, end);
  18. }
  19. }
  20.  
  21. if(data!==''){
  22. //$("#head_pic_btn").hide();
  23. //$("#head_img").show().attr('src',"${ctx}/upload/trainer_picture/"+data);
  24.  
  25. $("#head_img").attr("src","${ctx}/upload/trainer_picture/"+data);
  26. $("#head_img").attr("data-img",data);
  27.  
  28. /**
  29. data=JSON.parse( data.match(/{.+}/)[0] )
  30. if( data.result==='true' ){
  31. $('#head_pic_btn').hide();
  32. $('#head_img').show().attr('src',"${ctx}/upload/trainer_picture/"+data);
  33. };
  34. alert(data.resultDesc);
  35. */
  36. };
  37. }
  38. });
  39. });
  40. });

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

  1. //新增修改 验证提交
  2. $("#formId").validator({
  3. theme :"simple_bottom",
  4. valid: function(form){
  5. var tname=$(".dialog_title").text();
  6. if(tname.indexOf("修改")>=0){
  7. //修改保存
  8. //SaveEditTeacher();
  9. var labels = "";
  10. var index = 0;
  11. $(".labels").find("li").each(function(){
  12. if(index==0){
  13. labels += "'" + $(this).attr("data-id") + "'";
  14. }else{
  15. labels += ",'"+$(this).attr("data-id") + "'";
  16. }
  17. index++;
  18. });
  19.  
  20. 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 };
  21. $.ajax({
  22. url:"${ctx}/td/trainer/modify.do",
  23. type:"get",
  24. data:param,
  25. success:function(data){
  26. if(data.result=="true"){
  27. new AlertWin().initfn({
  28. "tipscon":data.resultDesc,
  29. "showtime":2000
  30. });
  31. $("#formId")[0].reset();
  32. addWin.close();
  33. }else{
  34. new AlertWin().initfn({
  35. "tipscon":data.resultDesc,
  36. "showtime":2000
  37. });
  38. }
  39. //table.load();
  40. table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val() } );
  41. }
  42. });
  43.  
  44. }else{
  45. //新增
  46. var labels = "";
  47. var index = 0;
  48. $(".labels").find("li").each(function(){
  49. if(index==0){
  50. labels += "'" + $(this).attr("data-id") + "'";
  51. }else{
  52. labels += ",'"+$(this).attr("data-id") + "'";
  53. }
  54. index++;
  55. });
  56.  
  57. 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 };
  58. $.ajax({
  59. url:"${ctx}/td/trainer/insert.do",
  60. type:"get",
  61. data:param,
  62. success:function(data){
  63. if(data.result=="true"){
  64. new AlertWin().initfn({
  65. "tipscon":data.resultDesc,
  66. "showtime":2000
  67. });
  68. $("#formId")[0].reset();
  69. addWin.close();
  70. }else{
  71. new AlertWin().initfn({
  72. "tipscon":data.resultDesc,
  73. "showtime":2000
  74. });
  75. }
  76. //table.load();
  77. table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val() } );
  78. }
  79. });
  80. }
  81. }
  82. });

五、Java后台代码:

  1. /**
  2. *
  3. * @Title: uploadHeadImg
  4. * @Description: 上传头像
  5. * @param @param file
  6. * @param @param xCoordinate
  7. * @param @param yCoordinate
  8. * @param @param width
  9. * @param @param imgName
  10. * @param @param height
  11. * @param @param request
  12. * @param @param model
  13. * @param @return
  14. * @return String
  15. * @throws
  16. */
  17. @RequestMapping(value = "/uploadHeadImg", produces = "text/plain;charset=UTF-8")
  18. @ResponseBody
  19. public String uploadHeadImg(@RequestParam(value = "img", required = false) MultipartFile file,
  20. @RequestParam(value = "xCoordinate", required = false) Integer xCoordinate,
  21. @RequestParam(value = "yCoordinate", required = false) Integer yCoordinate,
  22. @RequestParam(value = "width", required = false) Integer width,
  23. @RequestParam(value = "imgName", required = false) String imgName,
  24. @RequestParam(value = "height", required = false) Integer height, HttpServletRequest request, ModelMap model) {
  25.  
  26. String result = "";
  27. EmpMessageRes msg = new EmpMessageRes();
  28.  
  29. //获得工程下面upload资源包路径,当然这个包是已经存在的了
  30. String path = request.getSession().getServletContext().getRealPath("upload/trainer_picture");
  31.  
  32. //上传的图片的名称
  33. String fileName = file.getOriginalFilename();
  34. String newfileName = UUIDUtil.generateGUID() + fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
  35.  
  36. //下面是upload路径盘符的转化
  37. StringBuffer importPath = new StringBuffer();
  38. String temp[] = path.split("\\\\");
  39.  
  40. for (int i = 0; i < temp.length; i++) {
  41. importPath.append(temp[i]);
  42. importPath.append("/");
  43. }
  44.  
  45. importPath.append(newfileName);
  46. //看是否存在upload包,没有则会新建一个upload包,作为资源上传的路径
  47. File targetFile = new File(path, newfileName);
  48. if (!targetFile.exists()) {
  49. targetFile.mkdirs();
  50. }
  51.  
  52. try { //文件上传
  53. file.transferTo(targetFile);
  54. /**
  55. *利用工具类对图片进行裁剪
  56. */
            /**
  57. //String name = "D:\\image.jpg";
  58. if (xCoordinate != null && yCoordinate != null && width != null && height != null) {
  59. OperateImage o = new OperateImage(xCoordinate, yCoordinate, width, height);
  60. o.setSrcpath(importPath.toString());
  61. o.setSubpath(importPath.toString());
  62. File toCompress = new File(importPath.toString());
  63. o.cut();
  64. if (toCompress.length() / 1024 > 50)
  65. //将上传的图片进行压缩
  66. ImgUtil.createIcon(importPath.toString());
  67. }
           */
  68.  
  69.         File toCompress = new File(importPath.toString());
             if (toCompress.length() / 1024 > 50){
                //将上传的图片进行压缩
               ew ImageUtil().thumbnailImage(importPath.toString(), 360, 420, true); //180, 210
             }
  70. msg.setResult("true");
  71. msg.setResultDesc("头像上传成功");
  72. msg.setImgUrl(newfileName);
  73. //result = "originalFilename=" + fileName + ";imgUrl=" + msg.getImgUrl() + ";result=" + msg.getResult() + ";resultDesc=" + msg.getResultDesc();
  74.  
  75. result = msg.getImgUrl();
  76.  
  77. } catch (Exception e) {
  78. msg.setResult("false");
  79. msg.setResultDesc("头像上传失败");
  80. e.printStackTrace();
  81. }
  82. if (imgName != null) {
  83. File later = new File(path, imgName);
  84. if (later != null)
  85. later.delete();
  86. }
  87.  
  88. return result;
  89. }

效果如图:

生成缩略图:

  1. package com.dayhr.web.module.hr.td.elearn.common.util;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Graphics;
  5. import java.awt.Image;
  6. import java.awt.image.BufferedImage;
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.util.Arrays;
  10. import javax.imageio.ImageIO;
  11.  
  12. /**
  13. *
  14. * @ClassName:ImageUtil
  15. * @Description: 生成缩略图
  16. * @author:
  17. * @date:2015-3-31 下午3:20:27
  18. * @version 1.0
  19. */
  20. public class ImageUtil {
  21.  
  22. /**
  23. *
  24. * @Title: thumbnailImage
  25. * @Description: 根据图片路径生成缩略图
  26. * @param @param imgFile 原图片路径
  27. * @param @param w 缩略图宽
  28. * @param @param h 缩略图高
  29. * @param @param force 是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
  30. * @return void
  31. * @throws
  32. */
  33. public void thumbnailImage(String imagePath, int w, int h, boolean force) {
  34.  
  35. File imgFile = new File(imagePath);
  36.  
  37. if (imgFile.exists()) {
  38.  
  39. try {
  40.  
  41. // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
  42. String types = Arrays.toString(ImageIO.getReaderFormatNames());
  43. String suffix = null;
  44.  
  45. // 获取图片后缀
  46. if (imgFile.getName().indexOf(".") > -1) {
  47. suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
  48. }
  49.  
  50. // 类型和图片后缀全部小写,然后判断后缀是否合法
  51. if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0) {
  52. //System.out.println("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
  53. return;
  54. }
  55.  
  56. Image img = ImageIO.read(imgFile);
  57. if (!force) {
  58. // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
  59. int width = img.getWidth(null);
  60. int height = img.getHeight(null);
  61.  
  62. if ((width * 1.0) / w < (height * 1.0) / h) {
  63. if (width > w) {
  64. h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0)));
  65. //System.out.println("target image's size, width:" + w+ " height:" + h);
  66. }
  67. } else {
  68. if (height > h) {
  69. w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h / (height * 1.0)));
  70. //System.out.println("target image's size, width:" + w+ " height:" + h);
  71. }
  72. }
  73. }
  74.  
  75. BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  76. Graphics g = bi.getGraphics();
  77. g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
  78. g.dispose();
  79.  
  80. // 将图片保存在原目录
  81. ImageIO.write(bi, suffix, imgFile);
  82.  
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. }
  86.  
  87. }
  88. }
  89.  
  90. // public static void main(String[] args) {
  91. // new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 100, 150, false);
  92. // }
  93.  
  94. }

jquery.upload.js:

  1. var onChooseFile = ''; (function($) {
  2. var noop = function(){
  3. return true;
  4. };
  5. var frameCount = 0;
  6. var imgName = '';
  7. $.uploadDefault = {
  8. url: '',
  9. fileName: 'filedata',
  10. dataType: 'json',
  11. params: {},
  12. onSend: noop,
  13. exten: [],
  14. onComplate: noop
  15. };
  16.  
  17. $.upload = function(options) {
  18. var opts = $.extend(jQuery.uploadDefault, options);
  19. if (opts.url == '') {
  20. return;
  21. }
  22.  
  23. var canSend = opts.onSend();
  24. if (!canSend) {
  25. return;
  26. }
  27.  
  28. var frameName = 'upload_frame_' + (frameCount++);
  29. var iframe = $('<iframe style="position:absolute;height:0;width:0;" name="'+frameName+'" />');
  30. var form = $('<form method="post" style="display:none;" target="'+frameName+'" action="'+opts.url+'" name="form_'+frameName+'" enctype="multipart/form-data" />');
  31. // 选中文件, 提交表单(开始上传)
  32. upFile = function(fileInputDOM) {
  33. imgName = fileInputDOM.value;
  34. var extension = imgName.match(/\.[^\.]+$/)[0].toLowerCase(),ontest=false;
  35. if (options.exten !== undefined) {
  36. for(var i=0;i<options.exten.length;i++){
  37. if( extension===options.exten[i] ){
  38. ontest=true;
  39. };
  40. };
  41. if(!ontest){
  42. new Tips({
  43. "tipscon": "格式为" + options.exten.join(",") + ",请重新选择!"
  44. });
  45. opts.ie8&&parElement.append(oldElement)
  46. return false;
  47. };
  48. };
  49. form.submit();
  50.  
  51. };
  52. var oldElement,parElement,fileInput;
  53. if(opts.ie8){
  54. oldElement = $('#' + opts.fileElementId),parElement=oldElement.parent();
  55. $(oldElement).appendTo(form);
  56. }else{
  57. // form中增加数据域
  58. var formHtml = '<input type="file" name="' + opts.fileName + '" onchange="upFile(this)">';
  59. for (key in opts.params) {
  60. formHtml += '<input type="hidden" name="' + key + '" value="' + opts.params[key] + '">';
  61. }
  62. form.append(formHtml);
  63. }
  64.  
  65. $(document.body).append(form).append(iframe);
  66. opts.ie8&&upFile(oldElement[0]);
  67. // iframe 在提交完成之后
  68. iframe.load(function() {
  69. var data = $(this).contents().find('body').html();
  70. opts.onComplate(data, imgName);
  71. if(!data) return false;
  72. setTimeout(function() {
  73. opts.ie8&&parElement.append(oldElement)
  74. iframe.remove();
  75. form.remove();
  76. },300);
  77. });
  78.  
  79. // 文件框
  80. if(!opts.ie8){
  81. fileInput = $('input[type=file][name=' + opts.fileName + ']', form);
  82. fileInput.click();
  83. }
  84.  
  85. };
  86. })(jQuery);

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

  1. 上传系列:jquery.upload.js

    最近想做一个上传的总结,把自己用过的上传插件都写一写,哪天用到的时候就不用再一次的翻阅资料,现在页面上用到的上传插件,原理上都差不多,那我也就不再废话了,下面我主要记录一下几个比较常用的,由简到繁,这 ...

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

    前端: js:        function AjaxKouBeiShopEdit() { var options = {                dataType: "json&q ...

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

    一.建立Default.aspx页面 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile=&q ...

  4. ASP.Net MVC3 图片上传详解(form.js,bootstrap)

    图片上传的插件很多,但很多时候还是不能切合我们的需求,我这里给大家分享个我用一个form,file实现上传四张图片的小demo.完全是用jquery前后交互,没有用插件. 最终效果图如下: 玩过花田人 ...

  5. js上传视频(jquery.form.js)

    // 上传目标触发点 <input type="file" class="upvideo" name="upvideo" id=&qu ...

  6. 微信JS图片上传与下载功能--微信JS系列文章(三)

    概述 在前面的文章微信JS初始化-- 微信JS系列文章(一)中已经介绍了微信JS初始化的相关工作,接下来本文继续就微信JS的图片上传功能进行描述,供大家参考. 图片上传 $(function(){ v ...

  7. 头像文件上传 方法一:from表单 方法二:ajax

    方法一:from表单 html 设置form表单,内包含头像预览div,内包含上传文件input 设置iframe用来调用函数传参路径 <!--表单提交成功后不跳转处理页面,而是将处理数据返回给 ...

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

    (function($){ var methods = { init:function(options){ return this.each(function(){ var $this = $(thi ...

  9. ABAP分享十: 文件的上传 方法一

    前提条件:PARAMETERS P_files TYPE RLGRAP-FILENAME. AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_files.一.文件的 ...

  10. 支持图片上传预览的 uploadPreview.js 插件

    原文链接:http://www.lanrenzhijia.com/others/3148.html

随机推荐

  1. Linux命令应用大词典-第44章 PPPoE配置

    44.1 pppoe-setup:配置PPPoE客户端 44.2 ppoe-connect:管理PPPoE链路 44.3 pppoe-start:启动PPPoE链路 44.4 pppoe-stop:关 ...

  2. python学习笔记02 --------------基础数据类型

    python的基本数据类型: 1.基本数据 1.1. 数字类型 1.1.1 整数 int int()           #将括号内内容转化为整数类型. 1.1.2 浮点数 float 1.1.3 复 ...

  3. 孤荷凌寒自学python第七十七天开始写Python的第一个爬虫7

    孤荷凌寒自学python第七十七天开始写Python的第一个爬虫7 (完整学习过程屏幕记录视频地址在文末) 今天在上一天的基础上继续完成对我的第一个代码程序的书写. 今天的学习仍然是在纯粹对docx模 ...

  4. 文件上传:CommonsMultipartResolver

    一. 简介 CommonsMultipartResolver是基于Apache的Commons FileUpload来实现文件上传功能的,主要作用是配置文件上传的一些属性. 二. 配置 1)依赖Apa ...

  5. Wordcount -- MapReduce example -- Mapper

    Mapper maps input key/value pairs into intermediate key/value pairs. E.g. Input: (docID, doc) Output ...

  6. php性能优化--opcache

    一.OPcache是什么? OPcache通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能, 存储预编译字节码的好处就是 省去了每次加载和解析 PHP 脚本的开销. PHP 5 ...

  7. Python中的__future__

    在Python中,你如果在某一个版本的Python想使用未来版本中的功能,可以使用如下语法实现: from __future__ import futurename 这条语句必须放在module文件的 ...

  8. PHP 将一个字符串部分字符用$re替代隐藏

    <?php/** * 将一个字符串部分字符用$re替代隐藏 * @param string $string 待处理的字符串 * @param int $start 规定在字符串的何处开始, * ...

  9. android平台蓝牙编程(转)

    http://blog.csdn.net/pwei007/article/details/6015907 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样利用a ...

  10. iOS- iOS 7 的后台多任务 (Multitasking) 对比之前的异同、具体机制、变化

    简单来说,这玩意是对开发者友好,但对设备不友好的(可能会偷偷摸摸地占用流量和电量).对用户来说,如果你带宽够,对发热不敏感的话,会得到更好的应用体验. 从 iOS 4 开始,应用就可以在退到后台后,继 ...