手把手教你玩转上传图片

来源:互联网 发布:淘宝部分店铺无法使用 编辑:程序博客网 时间:2024/05/01 01:33

mvc 大家肯定比两下还要懂,那么我说从 jsp --> controller --> dao 三层,下面直接贴原代码:

一、V jsp 导入 ajaxfileupload.js:

1.1、前端Jsp: 

<img class="imgCursor" id="interImg" src="<%=path%>/images/noPricture.jpg" /><input type="file" src="" multiple="multiple" id="fileBtn1" class="hiddenFileBtn" accept="image/*" name="imgFile" style="display:none;"/>
1.2、Js:

$.ajax({    type:"post",    url:"saveArchive",    data:data,    success:function(data){        $("#DialogInfo").dialog('close');        if(data.code = "0003"){            $.messager.alert("信息提示",data.message,"info");            $('#viewList').datagrid('reload');        }else{            $.messager.alert("信息提示",data.message,"info");        }    }});

二、Controller:

/** * 上传图片 */@RequestMapping(value = "imageUpload", method = RequestMethod.POST)@ResponseBodypublic Map<String, Object> imageUpload(        @RequestParam(value = "imgFile", required = false) MultipartFile imgFile,        HttpServletRequest request) {    String tomcatPath = request.getServletContext().getRealPath("/");    String path = tomcatPath+"/images/" + DateUtil.getDateInfo()+"/img/";    File dir = new File(path);    if (!dir.exists()) {        dir.mkdirs();    }    String fileName = imgFile.getOriginalFilename();    String suffix = fileName.substring(fileName.lastIndexOf("."))            .toLowerCase();    String[] images = {".jpg",".jpeg",".png",".bmp",".ico",".gif"};// 定义图片格式数组    boolean flag = false;    for (int i = 0; i < images.length; i++) {        if(suffix.equals(images[i])){            flag = true;            break;        }    }    Map<String, Object> succMap = new HashMap<String, Object>();    String returnCode = null;    Boolean boole =true;    if(flag){        fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;        path = path + fileName;        File saveFile = new File(path);        try {            imgFile.transferTo(saveFile);            boole = ImageUtil.isImage(saveFile);            if(boole){                returnCode = ReturnCode.UPLOAD_SUCCESS.toString();                // FTP同步图片                if(PropertiesUtils.STATIC_IMGFTP_STATUS.equals("true")){//启用ftp同步                    ImageUtil ftp = new ImageUtil();                      ftp.ftpLogin();                          Boolean bool =  ftp.uploadFile(saveFile,"/images/" + DateUtil.getDateInfo()+"/img/");                    if(bool){                        returnCode = ReturnCode.UPLOAD_SUCCESS.toString();                    }else{                        returnCode = ReturnCode.UPLOAD_ERROR.toString();                    }                    //关闭上传                    ftp.ftpLogOut();                 }            }else{                 if (saveFile.exists()) {                       saveFile.delete();//删除文件                    }                  returnCode = ReturnCode.UPLOAD_ERROR.toString();            }        } catch (Exception e) {            e.printStackTrace();        }        String result = path.replace(tomcatPath, "");        succMap.put("url", result);    }else{        returnCode = ReturnCode.UPLOAD_ASTRICT.toString();    }    succMap.put("returnCode", returnCode);    return succMap;}
三、FTP:

/**  * Description: 向FTP服务器上传文件  * @param host FTP服务器hostname  * @param port FTP服务器端口  * @param username FTP登录账号  * @param password FTP登录密码  * @param basePath FTP服务器基础目录 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath * @param filename 上传到FTP服务器上的文件名  * @param input 输入流  * @return 成功返回true,否则返回false  */  public static boolean uploadFile(String host, int port, String username, String password, String basePath,String filePath, String filename, InputStream input) {boolean result = false;FTPClient ftp = new FTPClient();FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);conf.setServerTimeZoneId(TimeZone.getDefault().getID());  ftp.configure(conf);  try {int reply;ftp.connect(host, port);// 连接FTP服务器// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器ftp.login(username, password);// 登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return result;}//切换到上传目录if (!ftp.changeWorkingDirectory(basePath+filePath)) {//如果目录不存在创建目录String[] dirs = filePath.split("/");String tempPath = basePath;for (String dir : dirs) {if (null == dir || "".equals(dir)) continue;tempPath += "/" + dir;if (!ftp.changeWorkingDirectory(tempPath)) {if (!ftp.makeDirectory(tempPath)) {return result;} else {ftp.changeWorkingDirectory(tempPath);}}}}//设置上传文件的类型为二进制类型ftp.setFileType(FTP.BINARY_FILE_TYPE);ftp.enterLocalPassiveMode();ftp.setBufferSize(1024 * 20);  ftp.setDataTimeout(30 * 1000);  //上传文件if (!ftp.storeFile(filename, input)) {return result;}input.close();ftp.logout();result = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {ioe.printStackTrace();}}}return result;}
四、ImageUtil工具类:

package com.chinadatapay.util;import java.awt.Image;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.TimeZone;import javax.imageio.ImageIO;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPClientConfig;import org.apache.commons.net.ftp.FTPReply;import org.apache.log4j.Logger;public class ImageUtil {public ImageUtil(){ftpClient = new FTPClient();  }private static ImageUtil image=null;      //静态工厂方法       public static ImageUtil getInstance() {           if (image == null) {             image = new ImageUtil();           }            return image;      }   private FTPClient ftpClient;      private final static String strIp =PropertiesUtils.STATIC_IMG_IP;  //192.168.10.12    private final static int intPort =21;      private final static String user =PropertiesUtils.STATIC_IMG_USER;      private final static String password =PropertiesUtils.STATIC_IMG_PWD;        private static Logger logger = Logger.getLogger(ImageUtil.class.getName());          /**      * @return 判断是否登入成功      * */      public boolean ftpLogin() {          boolean isLogin = false;          FTPClientConfig ftpClientConfig = new FTPClientConfig();          ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());          this.ftpClient.setControlEncoding("GBK");          this.ftpClient.configure(ftpClientConfig);          try {              if (this.intPort > 0) {                  this.ftpClient.connect(this.strIp, this.intPort);              } else {                  this.ftpClient.connect(this.strIp);              }              // FTP服务器连接回答              int reply = this.ftpClient.getReplyCode();              if (!FTPReply.isPositiveCompletion(reply)) {                  this.ftpClient.disconnect();                  logger.error("登录FTP服务失败!");                  return isLogin;              }              this.ftpClient.login(this.user, this.password);              // 设置传输协议              this.ftpClient.enterLocalPassiveMode();              this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);              logger.info("恭喜" + this.user + "成功登陆FTP服务器");              isLogin = true;          } catch (Exception e) {              e.printStackTrace();              logger.error(this.user + "登录FTP服务失败!" + e.getMessage());          }          this.ftpClient.setBufferSize(1024 * 2);          this.ftpClient.setDataTimeout(30 * 1000);          return isLogin;      }        /**      * @退出关闭服务器链接      * */      public void ftpLogOut() {          if (null != this.ftpClient && this.ftpClient.isConnected()) {              try {                  boolean reuslt = this.ftpClient.logout();// 退出FTP服务器                  if (reuslt) {                      logger.info("成功退出服务器");                  }              } catch (IOException e) {                  e.printStackTrace();                  logger.warn("退出FTP服务器异常!" + e.getMessage());              } finally {                  try {                      this.ftpClient.disconnect();// 关闭FTP服务器的连接                  } catch (IOException e) {                      e.printStackTrace();                      logger.warn("关闭FTP服务器的连接异常!");                  }              }          }      }        /***      * 上传Ftp文件      * @param localFile 当地文件      * @param romotUpLoadePath上传服务器路径 - 应该以/结束      * */      public boolean uploadFile(File localFile, String romotUpLoadePath) {          BufferedInputStream inStream = null;          boolean success = false;          try {        Boolean bool =   ftpClient.changeWorkingDirectory(romotUpLoadePath);        if(bool == false){//如果不存在 创建文件夹        this.ftpClient.makeDirectory(romotUpLoadePath);          //通过远程命令 穿件一个files文件夹          boolean change = createDirectory(romotUpLoadePath , ftpClient) ;         if(!change){         logger.error("文件服务器切换工作目录失败");         }         }        this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径               inStream = new BufferedInputStream(new FileInputStream(localFile));               logger.info(localFile.getName() + "开始上传.....");               success = this.ftpClient.storeFile(localFile.getName(), inStream);               if (success == true) {                   logger.info(localFile.getName() + "上传成功");                   return success;               }          } catch (FileNotFoundException e) {              e.printStackTrace();              logger.error(localFile + "未找到");          } catch (IOException e) {              e.printStackTrace();          } finally {              if (inStream != null) {                  try {                      inStream.close();                  } catch (IOException e) {                      e.printStackTrace();                  }              }          }          return success;      }     /**     * 在ftp服务器创建目录     */ public static boolean createDirectory(String path, FTPClient ftpClient)throws IOException {boolean flag = false;String[] pathes = path.split("/");for (int i = 0; i < pathes.length; i++) {ftpClient.makeDirectory(pathes[i]);flag = ftpClient.changeWorkingDirectory(pathes[i]);}return flag;}     /***      * @上传文件夹      * @param localDirectory      *            当地文件夹      * @param remoteDirectoryPath      *            Ftp 服务器路径 以目录"/"结束      * */      public boolean uploadDirectory(String localDirectory,              String remoteDirectoryPath) {          File src = new File(localDirectory);          try {              remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";              this.ftpClient.makeDirectory(remoteDirectoryPath);              // ftpClient.listDirectories();          } catch (IOException e) {              e.printStackTrace();              logger.info(remoteDirectoryPath + "目录创建失败");          }          File[] allFile = src.listFiles();          for (int currentFile = 0; currentFile < allFile.length; currentFile++) {              if (!allFile[currentFile].isDirectory()) {                  String srcName = allFile[currentFile].getPath().toString();  //                uploadFile(new File(srcName), remoteDirectoryPath);              }          }          for (int currentFile = 0; currentFile < allFile.length; currentFile++) {              if (allFile[currentFile].isDirectory()) {                  // 递归                  uploadDirectory(allFile[currentFile].getPath().toString(),                          remoteDirectoryPath);              }          }          return true;      }      // FtpClient的Set 和 Get 函数      public FTPClient getFtpClient() {          return ftpClient;      }      public void setFtpClient(FTPClient ftpClient) {          this.ftpClient = ftpClient;      }      public static void main(String[] args) throws IOException {      ImageUtil ftp=new ImageUtil();         ftp.ftpLogin();          File file = new File("D:\\apache-tomcat-7.0.70\\wtpwebapps\\chinadatapay.user\\xml\\WebSite.xml");          ftp.uploadFile(file,"/xml/" + DateUtil.getDateInfo()+"/");        //上传文件夹          ftp.ftpLogOut();          System.out.println("上传成功");    }public static void testImageUp(String param){System.out.println("调用接口保存图片..."+param);}/**  * 通过读取文件并获取其width及height的方式,来判断判断当前文件是否图片,这是一种非常简单的方式。  *   * @param imageFile  * @return  */  public static boolean isImage(File imageFile) {      if (!imageFile.exists()) {          return false;      }      Image img = null;      try {          img = ImageIO.read(imageFile);          if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {              return false;          }          return true;      } catch (Exception e) {          return false;      } finally {          img = null;      }  }  }


1 0