基於Java的一個簡單的檔案上傳下載功能

來源:互聯網
上載者:User

標籤:架構   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的一個簡單的檔案上傳下載功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.