Java圖片上傳

來源:互聯網
上載者:User

標籤:manage   htm   dir   exce   ror   ext   type   led   multi   

最近閑來無事,就整理常用的功能,以下是項目中圖片上傳的功能,將圖片上傳到伺服器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 src="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&src="+$("#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();}

Java圖片上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.