1. 程式人生 > >使用spring上傳檔案或圖片,及檔案或目錄的刪除

使用spring上傳檔案或圖片,及檔案或目錄的刪除

首先是基於spring框架,在springMVC-servlet.xml中配置multipart型別解析器,具體配置如下:

	<!-- 設定上傳檔案最大值   1M=1*1024*1024(B)=1048576 bytes -->  
	<bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
		<property name="maxUploadSize" value="1048576" /> 
	 </bean>

其配置了一個多型別檔案解析器CommonsMultipartResolver,並配置了maxUploadSize屬性,設定上傳檔案佔用的最大容量。

當然,使用springMVC上傳檔案需要用到Apache開源上傳軟體包fileupload和io包,並將這兩個包依賴引入工程。如下圖:

  附上這兩個jar的連結:https://pan.baidu.com/s/1Qs32eGzjcuieh8HjveQiLQ 密碼:p8gj

 之後在controller層增加上傳檔案的介面,這裡以圖片為例。

 /**
   * 上傳圖片
   */
  @RequestMapping(value = "/touploadImg")
  public String touploadImg(Model model) throws Exception{
	  return "/two";//上傳路勁
  }  


   /**
   * 上傳圖片
   */
  @RequestMapping(value = "/uploadImg")
  public static String uploadImg(Model model,MultipartFile file) throws Exception {
		String aa = file.getOriginalFilename();
		aa = new String(aa.getBytes("ISO-8859-1"),"UTF-8");//轉碼
		String bb=null;
		if(file!=null&&aa!=null&&aa.length()>0){
			String path = "G:\\cesh\\";//檔案放置的資料夾
			File file1 = new File(path);
			if(!file1.exists()){//判斷檔案目錄是否存在,不在則新增
				file1.mkdirs();
			}
			
//			bb=System.currentTimeMillis()+aa.substring(aa.lastIndexOf("."));
			bb=System.currentTimeMillis()+aa;//以時間戳加圖片名的方式儲存圖片
			System.out.println(bb);
			File newfile = new File(path+bb);
			file.transferTo(newfile);
		}
		model.addAttribute("image",bb);//回顯剛剛上傳的圖片名稱
		return "/two";	//重回上傳頁面
  }

前端two.jsp的程式碼:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
  <%@ taglib prefix="fn" 
      uri="http://java.sun.com/jsp/jstl/functions" %>
  <%@ taglib prefix="c" 
      uri="http://java.sun.com/jsp/jstl/core" %>
<html>
	<head>
		<meta charset="utf-8">
		<title>上傳圖片測試</title>
	</head>
	<body>
		<form action="uploadImg.action" method="post" enctype="multipart/form-data">
			<c:if test="${image !=null }">
				<img src="/cesh/${image }" width=100 height=100/><br/>
			</c:if>
			<input type="file" name="file"/><br/>
			<input type="submit" value="上傳">
		</form>
	</body>


</html>

注:這裡返回的圖片路徑應該在tomcat中配置,不然是顯示404找不到該圖片路徑的。

即在tomcat目錄下的conf資料夾下的server.xml配置檔案,在最下方的Host標籤中新增以下配置:

<Context docBase="G:\upload" path="/cesh" reloadable="false"/>

這裡配置了當訪問“/cesh”路徑時,對映提供服務機器G盤的upload資料夾所在的目錄。

測試:啟動測試工程,在瀏覽器中輸入http://localhost:8080/Spring_test/touploadImg.action跳轉圖片上傳頁面。如下:

上傳成功後可以在G:/upload下找到剛剛上傳的圖片。

附:檔案或目錄的刪除:

/**
   * 刪除單個檔案
   *
   * @param fileName
   *            要刪除的檔案的檔名
   * @return 單個檔案刪除成功返回true,否則返回false
   */
  public static boolean deleteFile(String fileName) {
      File file = new File(fileName);
      // 如果檔案路徑所對應的檔案存在,並且是一個檔案,則直接刪除
      if (file.exists() && file.isFile()) {
          if (file.delete()) {
              System.out.println("刪除單個檔案" + fileName + "成功!");
              return true;
          } else {
              System.out.println("刪除單個檔案" + fileName + "失敗!");
              return false;
          }
      } else {
          System.out.println("刪除單個檔案失敗:" + fileName + "不存在!");
          return false;
      }
  }
  
  /**
   * 刪除目錄及目錄下的檔案
   *
   * @param dir
   *            要刪除的目錄的檔案路徑
   * @return 目錄刪除成功返回true,否則返回false
   */
  public static boolean deleteDirectory(String dir) {
      // 如果dir不以檔案分隔符結尾,自動新增檔案分隔符
      if (!dir.endsWith(File.separator))
          dir = dir + File.separator;
      File dirFile = new File(dir);
      // 如果dir對應的檔案不存在,或者不是一個目錄,則退出
      if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
          System.out.println("刪除目錄失敗:" + dir + "不存在!");
          return false;
      }
      boolean flag = true;
      // 刪除資料夾中的所有檔案包括子目錄
      File[] files = dirFile.listFiles();
      for (int i = 0; i < files.length; i++) {
          // 刪除子檔案
          if (files[i].isFile()) {
              flag = deleteFile(files[i].getAbsolutePath());
              if (!flag)
                  break;
          }
          // 刪除子目錄
          else if (files[i].isDirectory()) {
              flag = deleteDirectory(files[i]
                      .getAbsolutePath());
              if (!flag)
                  break;
          }
      }
      if (!flag) {
          System.out.println("刪除目錄失敗!");
          return false;
      }
      // 刪除當前目錄
      if (dirFile.delete()) {
          System.out.println("刪除目錄" + dir + "成功!");
          return true;
      } else {
          return false;
      }
  }

編寫一個主方法做測試用:

public static void main(String [] args) throws UnsupportedEncodingException{
	  	String fileName="G:\\upload";
	        File file = new File(fileName);
	        if (!file.exists()) {
	            System.out.println("刪除檔案失敗:" + fileName + "不存在!");
	        } else {
	            if (file.isFile())
	                deleteFile(fileName);
	            else
	                deleteDirectory(fileName);
	        }
  }