最近要做上傳下載,所以又把它翻出了,熟悉了一把,做了一下字節轉換的調整及上傳類型的限制,當然還有上傳路徑的限制。不過一直在考慮的問題是怎樣找到減少服務器壓力的具體方法,本列子貼出來是希望能給某些新手一些幫助,同時也希望各路大俠批評指點小弟的許多不足。
首先建立一個FileAction
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
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 此位置的form是javabeen的對象,這個javabeen中存取的圖片的相關信息
<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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "
<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>
轉自javaEye http://www.javaeye.com/topic/219585