FileAction html
package com.action; import org.apache.struts.action.*; import javax.servlet.http.*; import com.actionForm.FileActionForm; import org.apache.struts.actions.DispatchAction; import java.util.Date; import java.text.*; import org.apache.struts.upload.FormFile; import java.io.*; import java.net.URLEncoder; import com.dao.*; public class FileAction extends DispatchAction { private JDBConnection connection =new JDBConnection(); //如下方法實現文件的上傳 public ActionForward upLoadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward=null; Date date = new Date(); FileActionForm fileActionForm = (FileActionForm) form; //FormFile用於指定存取文件的類型 FormFile file = fileActionForm.getFile(); //獲取當前的文件 // 得到系統的絕對路徑 String dir = servlet.getServletContext().getRealPath("/image"); //我上傳的文件沒有放在服務器上。而是存在D:D:\\loadfile\\temp\\ String dir="D:\\loadfile\\temp\\"; int i = 0; String type = file.getFileName(); while(i!=-1){ //找到上傳文件的類型的位置,這個地方的是'.' i = type.indexOf("."); /* System.out.println(i);*/ /*截取上傳文件的後綴名,此時獲得了文件的類型*/ type = type.substring(i+1); } // 限制上傳類型爲jpg,txt,rar; if (!type.equals("jpg") && !type.equals("txt")&& !type.equals("bmp")) {//當上傳的類型不爲上述類型時,跳轉到錯誤頁面。 forward=mapping.findForward("error"); } else { // 將上傳時間加入文件名(這個地方的是毫秒數) String times = String.valueOf(date.getTime()); //組合成 time.type String fname = times + "." + type; //InInputStream是用以從特定的資源讀取字節的方法。 InputStream streamIn = file.getInputStream(); //建立讀取用戶上傳文件的對象 //獲得是字節數,即byte,咱們能夠直接用file.getFileSize(),也能夠在建立讀取對象時用streamIn.available(); // int ok=streamIn.available(); int ok=file.getFileSize(); String strFee = null; //這個地方是處理上傳的爲M單位計算時,下一個是以kb,在下一個是byte; if(ok>=1024*1024) { float ok1=(((float)ok)/1024f/1024f); DecimalFormat myformat1 = new DecimalFormat("0.00"); strFee = myformat1.format(ok1)+"M"; System.out.println(strFee+"M"); } else if(ok>1024 && ok<=1024*1024) { double ok2=((double)ok)/1024; DecimalFormat myformat2=new DecimalFormat("0.00"); strFee = myformat2.format(ok2)+"kb"; System.out.println(strFee+"kb"); } else if(ok<1024) { System.out.println("aaaaaaaaa"); strFee=String.valueOf(ok)+"byte"; System.out.println(strFee); } System.out.println( streamIn.available()+"文件大小byte"); //這個是io包下的上傳文件類 File uploadFile = new File(dir); //指定上傳文件的位置 if (!uploadFile.exists() || uploadFile == null) { //判斷指定路徑dir是否存在,不存在則建立路徑 uploadFile.mkdirs(); } //上傳的路徑+文件名 String path = uploadFile.getPath() + "\\" + fname; //OutputStream用於向某個目標寫入字節的抽象類,這個地方寫入目標是path,經過輸出流FileOutputStream去寫 OutputStream streamOut = new FileOutputStream(path); int bytesRead = 0; byte[] buffer = new byte[8192]; //將數據讀入byte數組的一部分,其中讀入字節數的最大值是8192,讀入的字節將存儲到,buffer[0]到buffer[0+8190-1]的部分中 //streamIn.read方法返回的是實際讀取字節數目.若是讀到末尾則返回-1.若是bytesRead返回爲0則表示沒有讀取任何字節。 while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) { //寫入buffer數組的一部分,從buf[0]開始寫入並寫入bytesRead個字節,這個write方法將發生阻塞直至字節寫入完成。 streamOut.write(buffer, 0, bytesRead); } // 關閉輸出輸入流,銷燬File流。 streamOut.close(); streamIn.close(); file.destroy(); String paths=path; System.out.println(paths); String fileName = Chinese.toChinese(fileActionForm.getFileName()); //獲取文件的名稱 //String fileSize = String.valueOf(file.getFileSize()); String fileDate = DateFormat.getDateInstance().format(date); String sql = "insert into tb_file values('" + fileName + "','" + strFee + "','" + fileDate + "','" + paths + "')"; connection.executeUpdate(sql); connection.closeConnection(); forward=mapping.findForward("upLoadFileResult"); } return forward; } //實現文件的下載 public ActionForward downFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String path = request.getParameter("path"); System.out.println(path+"111"); BufferedInputStream bis = null; BufferedOutputStream bos = null; OutputStream fos = null; InputStream fis = null; //若是是從服務器上取就用這個得到系統的絕對路徑方法。 String filepath = servlet.getServletContext().getRealPath("/" + path); String filepath=path; System.out.println("文件路徑"+filepath); File uploadFile = new File(filepath); fis = new FileInputStream(uploadFile); bis = new BufferedInputStream(fis); fos = response.getOutputStream(); bos = new BufferedOutputStream(fos); //這個就就是彈出下載對話框的關鍵代碼 response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(path, "utf-8")); int bytesRead = 0; //這個地方的同上傳的同樣。我就很少說了,都是用輸入流進行先讀,而後用輸出流去寫,惟一不一樣的是我用的是緩衝輸入輸出流 byte[] buffer = new byte[8192]; while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); fis.close(); bis.close(); fos.close(); bos.close(); return null; } }
FileActionForm java
package com.actionForm; import org.apache.struts.action.*; import org.apache.struts.upload.*; public class FileActionForm extends ActionForm { private String fileName;//上傳文件的名稱 private String fileSize;//上傳文件的大小 private String filePath;//上傳文件到服務器的路徑 private String fileDate;//上傳文件的日期 private FormFile file;//上傳文件 public String getFileName() { return fileName; } public FormFile getFile() { return file; } public String getFileSize() { return fileSize; } public String getFilePath() { return filePath; } public String getFileDate() { return fileDate; } public void setFileName(String fileName) { this.fileName = fileName; } public void setFile(FormFile file) { this.file = file; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public void setFilePath(String filePath) { this.filePath = filePath; } public void setFileDate(String fileDate) { this.fileDate = fileDate; } }
index.jsp sql
<table width="264" height="81" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="115" rowspan="4" align="center"><img src="<%=form.getFilePath()%>" width="100" height="100"></td> <td width="133" align="center">圖片名稱:<%=form.getFileName()%></td> </tr> <tr align="center"> <td>圖片大小:<%=form.getFileSize()%></td> </tr> <tr align="center"> <td>上傳日期:<%=form.getFileDate()%></td> </tr> <tr> <td align="center"><a href="fileAction.do?method=downFile&path=<%=form.getFilePath()%>" ><img src="priture/bottond.jpg"></a> </td> </tr> </table> <html:form action="fileAction.do?method=upLoadFile" enctype="multipart/form-data" onsubmit="return Mycheck()"> <table height="52" border="0" align="center" cellpadding="0" cellspacing="0"> <tr align="center"> <td width="60" height="26">圖片名稱:</td> <td width="160"> <html:text property="fileName"/> </td> <td width="60">圖片路徑:</td> <td width="198"> <html:file property="file"/> </td> </tr> <tr align="right"> <td height="26" colspan="4"> <html:submit>上傳</html:submit> </td> </tr> </table> </html:form>
struts-config.xml
apache
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="fileActionForm" type="com.actionForm.FileActionForm" /> </form-beans> <action-mappings> <action name="fileActionForm" parameter="method" path="/fileAction" scope="request" type="com.action.FileAction" validate="true"> <forward name="upLoadFileResult" path="/result.jsp"/> <forward name="error" path="/fail.jsp"></forward> </action> </action-mappings> <message-resources parameter="ApplicationResources" /> </struts-config>