为了账号安全,请及时绑定邮箱和手机立即绑定

Java图片上传

标签:
Java

最近闲来无事,就整理常用的功能,以下是项目中图片上传的功能,将图片上传到服务器tomcat下,数据库中存放相对路径,大家一起学习。

环境:eclipse jdk1.7 tomcat7 maven3.5


步骤:

@RequestMapping(params="upLoadPicture")     @ResponseBody    public String addFilemsgPic(MultipartFile file,HttpServletRequest request) throws Exception{                String path="../Manage_ssm/upLoadPicture";                //创建文件         File dir=new File(path);        if(!dir.exists()){            dir.mkdirs();        }                String username=(String) request.getSession().getAttribute("userName");        //返回原来在客户端的文件系统的文件名        String fileName=file.getOriginalFilename();        //username+后缀名            String img=username+fileName.substring(fileName.lastIndexOf("."));//zhao.jpg        FileOutputStream imgOut=new FileOutputStream(new File(dir,img));//根据 dir 抽象路径名和 img 路径名字符串创建一个新 File 实例。                imgOut.write(file.getBytes());//返回一个字节数组文件的内容        imgOut.close();        Map<String, String> map=new HashMap<String, String>();            String rpath = path+"/"+img;        map.put("rPath",rpath);        JSONObject jsonObject = JSONObject.fromObject(map);//将json字符串转换为json对象        String r=jsonObject.toString();        String s=URLEncoder.encode(r, "utf-8");//加密        return s;    }
@RequestMapping(params="pictureToDb")     @ResponseBody    public int pictureToDb(String src,HttpServletRequest request){                   String newSrc = src.replace(" ", "+");        int flag=ConnOrcl.connToTable(newSrc,request);        if(flag==1)            return 1;        else            return 2;    }
public class ConnOrcl {            private static Connection conn;          private static Statement stat;          private static String driver = "oracle.jdbc.driver.OracleDriver";          private static int SUCCESS=1;         private static int FILE=2;         public static int connToTable(String file,HttpServletRequest request)          {              try              {                  //数据库连接                  Class.forName(driver);                  conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "GKBMFZXT", "GKBMFZXT");                  stat = conn.createStatement();                                 String username=(String) request.getSession().getAttribute("userName");                             String sql="update user_table set picture='"+file+"' where user_name='"+username+"'";                      stat.execute(sql.toString());                                     return SUCCESS;            }              catch(ClassNotFoundException e)              {                  e.printStackTrace();              }              catch(SQLException e)              {                  e.printStackTrace();              }              finally              {                  if(null != stat)                  {                      try                       {                          stat.close();                      }                       catch (SQLException e)                      {                          e.printStackTrace();                      }                  }                  if(null != conn)                  {                      try                       {                          conn.close();                      }                       catch (SQLException e)                       {                          e.printStackTrace();                      }                  }              }              return FILE;        } }
<script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/ajaxfileupload.js"></script><script type="text/javascript">function upload(){        var file="file";    var picElement=document.getElementById(file).value;        var picFormat=picElement.substring(picElement.lastIndexOf('.')+1,picElement.length);    if(picFormat!="jpg"){        alert("请选择jpg 格式的文件!");        return;    }    $.ajaxFileUpload({             url:"user.do?upLoadPicture",           secureuri: false,           fileElementId:file,           dataType: 'JSON',           success:function(data){                  data=decodeURIComponent(data);//解码                  var arr=JSON.parse(data);//JSON.parse() 方法解析一个JSON字符串                            $("#fsrc").val(arr.rPath);                          $.post(                        "user.do?pictureToDb&class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="+$("#fsrc").val(),                            function(data){                            //data=decodeURIComponent(data);                            //var arr=JSON.parse(data);                            if(data==1){                            alert("上传成功!");                            }else{                            alert("上传失败!");                            }                        }                    );         },        error: function (){               alert("上传失败!当前时间为:"+new Date().toLocaleTimeString());                 }    });};function findFile(){    document.getElementById("file").click();}


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消