Spring Mvc 上传图片代码

  图片:  <form:hidden path= "picPath" id= "picPath" ></form:hidden>
       <span id= "${uuid}-statusPic" style= "color: #666;" >
       预览</span>
       修改
      
 
 
<!-- 点击修改调出窗口 -->
 
<div id= "${uuid}-uploadWindow" class = "easyui-window" title= "图片上传" modal= "true" resizable= "false" collapsible= "false" minimizable= "false" maximizable= "false" closed= "true" style= "width:520px;height:100px;padding:5px;background: #fafafa;" >
         <div class = "easyui-layout  with iframe" fit= "true" >
             <div region= "center" border= "false" style= "padding:10px;background:#fff;border:1px solid #ccc;" >
                 <form action= "menu/SmartMenu.do?action=uploadFile" method= "post" enctype= "multipart/form-data" style= "color: #666;" id= "${uuid}-tforma" >
                    <input name= "picPath" id= "${uuid}-picPath" value= "${command.picPath}" type= "hidden" >
                       图片路径: <input name= "itemPic" alt= "\" accept=" image/* " id=" ${uuid}-itemPic " type=" file ">图片大小不超过2M<input class=" easyui-linkbutton " value=" 上传 " type=" submit">
                  </form>
             </div>
         </div>
     </div>
 
<!-- 页面刚刚加载时调用 -->
 
init: function(uuid) {
     // this.identifier 是设定的全局变量,uuid是页面加载时的唯一编码
     this .identifier = uuid;
     // 图片上传
     var idf = this .identifier;
     var that = this ;
     $( '#' +idf+ '-tforma' ).ajaxForm({
         dataType : 'json' ,
     beforeSubmit : function(a, f, o) {
       $( '#' +idf+ '-statusPic' ).html( '上传中...' );
     },
         success : function(data) { 
      if (typeof (data) == 'string' )
        data = eval( '(' + data + ')' );
      $( '#' +idf+ '-uploadWindow' ).window( 'close' );
      if ( "success" == data.message) {
          $( 'div[identifier=' +that.identifier+ ']' ).find( '#picPath' ).val(data.path);
          $( "#" +idf+ "-path" ).val(data.path);
          $( "#" +idf+ "-statusPic" ).html( "预览" );
      } else if ( "error" == data.message)
          $( "#" +idf+ "-statusPic" ).html( "非图片数据!" );
      else
          $( "#" +idf+ "-statusPic" ).html( "上传数据错误!" );
           $( "#" +idf+ "-itemPic" ).val( '' );
      },
      error : function(jqXHR, textStatus,errorThrown) {
          $( '#$' +idf+ '-uploadWindow' ).window( 'close' );
          //console.log("error:"+ data.responseText);
          //console.log("status:" + textStatus);
          $( "#" +idf+ "-statusPic" ).html( "上传失败!" );
          $( "#" +idf+ "-itemPic" ).val( '' );
      } });
     }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
      * <b>商品上传指定的图片</b>
      *
      * @param request
      * @param response
      * @param command
      * @return
      * @throws Exception
      */
     public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response, SmartMenu command) throws Exception {
         PrintWriter writer = null ;
         try {
             response.setContentType( "application/json; charset=GBK" );
             writer = response.getWriter();
 
             MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
             String source = request.getSession().getServletContext().getRealPath( "/" );
             // 获得第1张图片(根据前台的name名称得到上传的文件)
             MultipartFile imgFile1 = multipartRequest.getFile( "itemPic" );
             // 判断是否是重复上传图片(如果重复将删除旧图片)
             String sourceImg = request.getParameter( "path" );
             if (imgFile1.getContentType().split( "/" )[ 0 ].equals( "image" )) {
                 if ( null != sourceImg && ! "" .equals(sourceImg)) {
                     System.out.println( "旧图片路径:" + sourceImg);
                     File f = new File(source + sourceImg);
                     if (f.isFile()) {
                         f.delete();
                         System.out.println( " 删除成功" );
                     } else
                         System.out.println( " 删除失败!" );
                 }
                 String path = null ;
                 if (imgFile1 != null && imgFile1.getSize() > 0 ) {
                     path = this .getSmartMenuService().storeFile(request.getSession(), imgFile1);
                 }
                 writer.print( "{\"message\":\"success\",\"path\":\"" + path.replace( "\\" , "\\\\" ) + "\"}" );
             } else
                 writer.print( "{\"message\":\"error\"}" );
         } catch (Exception e) {
             // TODO: handle exception
             writer.print( "{\"message\":\"no\"}" );
         }
         writer.flush();
         writer.close();
         return null ;
     }
 
 
     @Override
     public String storeFile(HttpSession session, MultipartFile file) throws Exception {
         // TODO Auto-generated method stub
         String fileType = file.getContentType().split( "/" )[ 1 ];
         String path = session.getServletContext().getRealPath( "/" );
         String separator = File.separator;
         String uuid = UUID.randomUUID().toString();
         FileOutputStream fos = null ;
         String fileName = null ;
         try {
             InputStream fis = file.getInputStream();
             // 转换文件为png格式,并保存在同名目录下
             File files = new File(path + "\\dishpic" );
             // 判断文件夹是否存在,如果不存在则创建文件夹
             if (!files.exists()) {
                 files.mkdir();
             }
             if (file.getContentType().split( "/" )[ 0 ].equals( "image" )) {
                 if (path.endsWith(separator))
                     fileName = path + "dishpic" + separator + uuid + ".png" ;
                 else
                     fileName = path + separator + "dishpic" + separator + uuid + ".png" ;
                 fos = new FileOutputStream(fileName);
                 ImageUtil.convertFormat(fis, fos, fileType, "png" , 0 , 0 );
                 fos.flush();
                 fos.close();
             }
         } catch (Exception ex) {
             System.out.println( "文件取出失败,错误信息: " + ex.getMessage());
             if (fos != null )
                 fos.close();
             throw ex;
         }
         return "dishpic" + separator + uuid + ".png" ;
     }
     
 
 
 
 
 
/**
  * <b>1.对图片时行格式转换</b><br>
  * <b>2.对图片进行适度的大小裁剪</b>
  *
  */
public class ImageUtil {
 
     /**
      *
      * @param infile 输入文件
      * @param outfile 输出文件
      * @param srcFormat 源格式
      * @param destFormat 输出格式
      * @return
      * @throws Exception
      */
     public static boolean convertFormat(InputStream infile,
             OutputStream outfile, String srcFormat, String destFormat, int width , int height) throws Exception {
         boolean flag = false ;
         BufferedImage src = ImageIO.read(infile);
         if (height > 0  && width > 0 ) { // compress the origin image if width and height are non-zero
             height = src.getHeight() > height ? height: src.getHeight();
             width = src.getWidth() > width ? width : src.getWidth();
             Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT); //这个是用来进行图片大小调整的
     
             BufferedImage tag = new BufferedImage(width, height,
                     BufferedImage.TYPE_INT_RGB);
     
             Graphics g = tag.getGraphics();
             //可在下面对图片进行绘制和更改
             g.drawImage(image, 0 , 0 , null ); // 绘制缩小后的图
     
             g.dispose();
             tag.flush();
             flag = ImageIO.write(tag, destFormat, outfile); // 输出到经过缩放的文件流
         } else {
             flag = ImageIO.write(src, destFormat, outfile); //输出原分辨率的图片
         }
         Logger.getLogger(ImageUtil. class ).info( "图片转换成功: 从[" + srcFormat + "]到[" + destFormat + "]" );
         return flag;
     }
}

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!-- xml中要配置这段代码 -- >
 
     <bean id= "multipartResolver"
         class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" >
         <property name= "maxUploadSize" >
             <value> 2048576 </value>
         </property>
     </bean></pre><br>
<br>
<p>该代码是经测试使用的源码,但是还存在问题!我直接截的图片能够上传,修改过的图片不能上传,会报错</p>
<p>在</p>
<pre class = "brush:java;" >BufferedImage src = ImageIO.read(infile);</pre>ImageIO读jpg的时候出现javax.imageio.IIOException: Unsupported Image Type  !<br>
<p></p>
<br>
<p></p>
<p><br>
</p>                        </dd></dl>
         <script type= "text/javascript" >
         <!--
         $(function(){
           $( '#Article img' ).LoadImage( true , 630 , 560 , 'http://www.2cto.com/statics/images/s_nopic.gif' );   
         })
         
         //-->
         
     <div id= "pages" class = "box_body" >   </div>
     <dl style= "width:650px;height:100px;padding-top:10px;float:left;padding-left:10px" >
         <dd><script type= "text/javascript" >BAIDU_CLB_fillSlot( "771048" );</script><div id= "BAIDU_DUP_wrapper_771048_0" ><iframe src= "http://cb.baidu.com/ecom?cec=gbk&dai=4&cfv=13&cpa=1&col=zh-CN&dis=0&xuanting=0&n=cnrhucpr&conOP=0&scale=&skin=tabcloud_skin_1&rsi0=640&rsi1=90&rsi5=4&ltr=http%3A%2F%2Fwww.baidu.com%2Fs%3Ftn%3Dmonline_5_dg%26ie%3Dutf-8%26wd%3Dspring%2520%2520%2520%25E4%25B8%258A%25E4%25BC%25A0%25E5%259B%25BE%25E7%2589%2587%2520%25E4%25BB%25A3%25E7%25A0%2581%26f%3D8%26bs%3Dspring%2520%253Cinput%2520type%253D%2522file%2522%2520%25E4%25B8%258A%25E4%25BC%25A0%25E5%259B%25BE%25E7%2589%2587%26rsv_bp%3D1%26inputT%3D14508%26rsv_sug3%3D12%26rsv_sug4%3D377%26rsv_sug1%3D6%26rsv_sug2%3D0&ltu=http%3A%2F%2Fwww.2cto.com%2Fkf%2F201312%2F267934.html&pcs=1349x610&rss0=&rss1=&rss2=&rss3=&rss4=&rss5=&rss6=&rss7=&rad=&pis=10000x10000&aurl=&psr=1366x768&pss=1349x6016&stid=5&tpr=1406094414097&lunum=6&ch=0&at=103&qn=a2e2d6cc686b5cdc&ps=5911x215&rs=301&tn=baiduCustSTagLinkUnit&ts=1&td_id=9223372032564469692&adn=0&cad=1&ccd=24&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=771048" marginwidth= "0" marginheight= "0" scrolling= "no" allowtransparency= "true" align= "center,center" frameborder= "0" height= "90" width= "640" ></iframe></div><script charset= "utf-8" src= "http://cb.baidu.com/ecom?di=771048&dcb=BAIDU_DUP_define&dtm=BAIDU_DUP2_SETJSONADSLOT&dbv=0&dci=0&dri=0&dis=0&dai=4&dds=&drs=1&dvi=7o&ltu=http%3A%2F%2Fwww.2cto.com%2Fkf%2F201312%2F267934.html&liu=&ltr=http%3A%2F%2Fwww.baidu.com%2Fs%3Ftn%3Dmonline_5_dg%26ie%3Dutf-8%26wd%3Dspring%2520%2520%2520%25E4%25B8%258A%25E4%25BC%25A0%25E5%259B%25BE%25E7%2589%2587%2520%25E4%25BB%25A3%25E7%25A0%2581%26f%3D8%26bs%3Dspring%2520%253Cinput%2520type%253D%2522file%2522%2520%25E4%25B8%258A%25E4%25BC%25A0%25E5%259B%25BE%25E7%2589%2587%26rsv_bp%3D1%26inputT%3D14508%26rsv_sug3%3D12%26rsv_sug4%3D377%26rsv_sug1%3D6%26rsv_sug2%3D0&lcr=http%3A%2F%2Fwww.baidu.com%2Fs%3Ftn%3Dmonline_5_dg%26ie%3Dutf-8%26wd%3Dspring%2520%2520%2520%25E4%25B8%258A%25E4%25BC%25A0%25E5%259B%25BE%25E7%2589%2587%2520%25E4%25BB%25A3%25E7%25A0%2581%26f%3D8%26bs%3Dspring%2520%253Cinput%2520type%253D%2522file%2522%2520%25E4%25B8%258A%25E4%25BC%25A0%25E5%259B%25BE%25E7%2589%2587%26rsv_bp%3D1%26inputT%3D14508%26rsv_sug3%3D12%26rsv_sug4%3D377%26rsv_sug1%3D6%26rsv_sug2%3D0&ps=5911x215&psr=1366x768&par=1366x728&pcs=1349x610&pss=1349x6016&pis=-1x-1&cfv=13&ccd=24&chi=1&cja=false&cpl=32&cmi=37&cce=true&col=zh-CN&cec=gbk&cdo=-1&tsr=2009&tlm=1388043197&tcn=1406094416&tpr=1406094414097&dpt=none&coa=&baidu_id=" ></script><script charset= "utf-8" src= "http://dup.baidustatic.com/painter/union/inlayFixed.js" ></script></dd>
     </dl>
     <dl class = "box_Nsc" >
         <dd class = "lcopy" >点击复制链接 与好友分享!回本站首页</dd>
         <script>
         function copyToClipBoard(){
         var clipBoardContent=document.title + '\r\n' + document.location;
         clipBoardContent+= '\r\n' ;
         window.clipboardData.setData( "Text" ,clipBoardContent);
         alert( "恭喜您!复制成功" );
         }
         </script>
 
         <div class = "Article-Tool" >
                                   <!-- Baidu Button BEGIN -->
<div id= "bdshare" class = "bdshare_t bds_tools get-codes-bdshare" > <span style= "float:left" >分享到:</span>
 
 
 
 
 
 
 
 
<span class = "bds_more" >更多</span>
</div>
<script src= "http://bdimg.share.baidu.com/static/js/bds_s_v2.js?cdnversion=390582" type= "text/javascript" id= "bdshare_js" data= "type=tools&uid=12732" ></script>
 
<script type= "text/javascript" >
var bds_config = { 'snsKey' :{ 'tsina' : '2386826374' , 'tqq' : '5e544a8fdea646c5a5f3967871346eb8' }};
document.getElementById( "bdshell_js" ).src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil( new Date()/ 3600000 )
</script>
<!-- Baidu Button END -->
                                 
       </div>
 
         
         </dl>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值