struts2文件上傳的采用的三種方式解析
文件上傳幾乎是每個(gè)項(xiàng)目實(shí)現(xiàn)的一個(gè)必須的模塊。
上傳就是將信息從個(gè)人計(jì)算機(jī)(本地計(jì)算機(jī))傳遞到中央計(jì)算機(jī)(遠(yuǎn)程計(jì)算機(jī))系統(tǒng)上,讓網(wǎng)絡(luò)上的人都能看到。將制作好的網(wǎng)頁、文字、圖片等發(fā)布到互聯(lián)網(wǎng)上去,以便讓其他人瀏覽、欣賞。這一過程稱為上傳。
JAVA實(shí)現(xiàn)文件上傳的幾個(gè)組件:
1 SmartUpload 用的最多的一個(gè)組件,已經(jīng)不再更新了,可以實(shí)現(xiàn)上傳和下載
2 FileUpload Apache實(shí)現(xiàn)的文件上傳組件,功能齊備
3 J2KUpload java2000實(shí)現(xiàn)的文件上傳組件,全部使用內(nèi)存,適合多個(gè)不超過10M的小文件
下面具體說說FileUpload Apache實(shí)現(xiàn)的文件上傳組件。
1、/** 按copy方式上傳 */
Java代碼
- public String uploadFile(){
- /**保存的具體路徑*/
- String savepath = getSavePath();
- /**根據(jù)保存的路徑創(chuàng)建file對象*/
- File file = new File(savepath);
- if(!file.exists()){
- /**創(chuàng)建此文件對象路徑*/
- file.mkdirs();
- }
- try {
- /**使用的是:org.apache.commons.io.FileUtils FileUtils*/
- FileUtils.copyFile(pic, new File(file,getPicFileName()));
- } catch (IOException e) {
- e.printStackTrace();
- }
- return SUCCESS;
- }
備注:
1、getSavePath()方法中,ServletActionContext().getServletContext().getRealPath
(savePath+"\\"+getPicFileName()); ,這個(gè)主要是一個(gè)文件的實(shí)際路徑
2、我個(gè)人認(rèn)為這種方式是簡單易用的。按copy方式上傳使用的是Apache公司的
org.apache.commons.io.FileUtils包里的FileUtils.java。
2、/** 按字節(jié)方式上傳 */
Java代碼
- public String uploadFile(){
- /** 文件的寫操作 */
- FileInputStream fis = null;
- FileOutputStream fos = null;
- /** 保存的路徑 */
- String savepath = getSavePath();
- /** 根據(jù)保存的路徑創(chuàng)建file對象 */
- File file = new File(savepath);
- /** file對象是否存在 */
- if (!file.exists()) {
- /** 創(chuàng)建此文件對象路徑 */
- file.mkdirs();
- }
- try {
- /** 創(chuàng)建輸入流 */
- fis = new FileInputStream(pic);
- /** 輸出流 更據(jù)文件的路徑+文件名稱創(chuàng)建文件對象 */
- fos = new FileOutputStream(file + "//" + getPicFileName());
- /** 讀取字節(jié) */
- byte b[] = new byte[1024];
- int n = 0;
- /** 讀取操作 */
- while ((n = fis.read(b)) != -1) {
- /** 寫操作 */
- fos.write(b, 0, n);
- }
- /** 關(guān)閉操作 */
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return SUCCESS;
- }
3、/** 按字符方式上傳 即“三層管道” */
Java代碼
- public String uploadFile(){
- /** 文件的寫操作 */
- BufferedReader br =null;
- BufferedWriter bw = null;
- /** 保存的路徑 */
- String savepath = getSavePath();
- /** 根據(jù)保存的路徑創(chuàng)建file對象 */
- File file = new File(savepath);
- /** file對象是否存在 */
- if (!file.exists()) {
- /** 創(chuàng)建此文件對象路徑 */
- file.mkdirs();
- }
- try {
- /** 創(chuàng)建一個(gè)BufferedReader 對象*/
- br = new BufferedReader(new InputStreamReader(new FileInputStream
- (pic)));
- bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream
- (file + "//" + getPicFileName())));
- // 讀取字節(jié)
- char b[] = new char[1024];
- int n = 0;
- // 讀取操作
- while ((n = br.read(b)) != -1) {
- // 寫操作
- bw.write(b, 0, n);
- }
- // 關(guān)閉操作
- if (br != null) {
- br.close();
- }
- if (bw != null) {
- bw.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return SUCCESS;
- }
備注:
第二種上傳方式?jīng)]有第三種上傳方式效率高。
建議:
***用***種方式上傳,次之使用第三種方式上傳,***再使用第二種方式上傳。