標籤:架構 springmvc mybatis 源碼 ehcache
最近在公司給用戶端做介面,有一個圖片上傳和檔案下載的功能,本來想用Struts來做檔案上傳下載,但是看了下公司好像沒有這個配置,然後看了下同事的代碼,才發現原來Apache也可以簡單的實現檔案上傳下載。
首先引入commons-io-2.2.jar
FileUtils為我們提供了很多對檔案的操作的方法,比如上傳整個檔案夾的檔案、上傳單個檔案等
然後請看代碼下載:
public static void uploadFile(String targetDirectory,String targetFileName,File file){
try {
File target = new File(targetDirectory, targetFileName);
/**
* 上傳整個檔案夾檔案
* */
//FileUtils.copyDirectory(file,target);
/**
* 上傳單個檔案
* */
FileUtils.copyFile(file, target);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
到這為止 一個簡單的檔案上傳就完成了。接下來看看下載檔案:
public static void downloadUrl(String httpurl,String targetDirectory){
try {
FileUtils.copyURLToFile(new URL(httpurl),
new File(targetDirectory));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
然後來一個man方法測試是否正確:
public static void main(String[] args) {
//上傳
File file = new File("D:/tp/xiazai.png");
FileUtil.uploadFile("D:/Test/", "uplod2016.png",file);
//下載
FileUtil.downloadUrl("http://img5.pcpop.com/ArticleImages/500x375/1/1613/001613973.jpg","D:/Test/jams.png");
}
上傳成功:
650) this.width=650;" src="http://dl2.iteye.com/upload/attachment/0121/4424/f186f57c-7eb5-393c-96be-1ce3ef609381.png" style="border:0px;font-family:Helvetica, Tahoma, Arial, sans-serif;font-size:14px;line-height:25.2px;white-space:normal;background-color:rgb(255,255,255);" alt="f186f57c-7eb5-393c-96be-1ce3ef609381.png" />
下載成功:
650) this.width=650;" src="http://dl2.iteye.com/upload/attachment/0121/4427/226371a7-fcb7-3a42-be5c-a75a13d6f0f3.png" style="border:0px;font-family:Helvetica, Tahoma, Arial, sans-serif;font-size:14px;line-height:25.2px;white-space:normal;background-color:rgb(255,255,255);" alt="226371a7-fcb7-3a42-be5c-a75a13d6f0f3.png" />
完美。
基於Java的一個簡單的檔案上傳下載功能