Java文件上傳的兩種簡單方法

第一種:上傳方法需要兩個類

第一個UploadFileImg類

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class UploadFileImg extends ActionForm {

private static final long serialVersionUID = 1L;

private String filePath;//--http://連接路徑

private String Memo;//--文件物理路徑--------

private FormFile uploadfile;

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public String getMemo() {
return Memo;
}

public void setMemo(String memo) {
Memo = memo;
}

public FormFile getUploadfile() {
return uploadfile;
}

public void setUploadfile(FormFile uploadfile) {
this.uploadfile = uploadfile;
}
}

第二個類UploadFileAction

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import com.common.upload.UploadFile;
public class UploadFileAction extends DispatchAction {

public ActionForward uploadImg(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UploadFileImg uploadFile=(UploadFileImg)form;
FormFile formFile=uploadFile.getUploadfile();
if(formFile==null){
return new ActionForward("/index.jsp");
};
UploadFile uploadFilet=new UploadFile();
String filePath=request.getSession().getServletContext().getRealPath("/")+"photo/";
String filename=formFile.getFileName();
String uploadFilePath="UploadFile/"+filename;//---上傳文件的相對路徑--
uploadFilet.UploadCommonFile(formFile.getInputStream(), filePath, filename);

return new ActionForward("/load.jsp");
}

}

需要注意的是這裏需要把common.jar這個包導入到你的lib目錄裏面去

load.jsp頁面

<table width="400" cellpadding="0" cellspacing="0" align="center" class="query_form_table">
<tr>
<td align="center"  class="borderleft bordertop borderright">
上傳文件
<input type="file" name="uploadfile"  οnchange="CheckExt(this,'img')"/>
<input type="button" class="button"  value="上傳" οnclick="JsSave('/Test/upload.do?

method=uploadImg')"/>
</td>
</tr>
<tr>
<td align="left" height="30" colspan="2" class="borderleft bordertop borderright ">    
<div style="border:1 solid 

#808080;background:#E0E0E0;width100%;height:20px;color:#606060;padding:5px;">
<table border="0" class="query_form_table">

第二種方法只需要兩個jsp頁面就可以了
第一個aa.jsp

<body>
<style>
.fu_list {
width: 500px;
background: #ebebeb;
font-size: 12px;
}

.fu_list td {
padding: 5px;
line-height: 20px;
background-color: #fff;
}

.fu_list table {
width: 100%;
border: 1px solid #ebebeb;
}

.fu_list thead td {
background-color: #f4f4f4;
}

.fu_list b {
font-size: 14px;
}

/*file容器樣式*/
a.files {
width: 90px;
height: 30px;
overflow: hidden;
display: block;
border: 1px solid #BEBEBE;
background: url(img/fu_btn.gif) left top no-repeat;
text-decoration: none;
}

a.files:hover {
background-color: #FFFFEE;
background-position: 0 -30px;
}

/*file設爲透明,並覆蓋整個觸發面*/
a.files input {
margin-left: -350px;
font-size: 30px;
cursor: pointer;
filter: alpha(opacity = 0);
opacity: 0;
}

/*取消點擊時的虛線框*/
a.files,a.files input {
outline: none; /*ff*/
hide-focus: expression(this . hideFocus = true); /*ie*/
}
</style>
<script language="javascript">
function filecheck()
{
filename=document.upload.file.value;
filenamelength=filename.length;

if (filename!="")
{
if (filename.substring((filename.lastIndexOf(".") + 1))!="rtf")
{
alert("對不起,只能上傳rtf文件");
return false;
}else 
return true;
}else{
alert("請選擇上傳文件!");
return false;
}
}

</script>
<form name="upload" method="post" action="../../FileUpload"
enctype="multipart/form-data" onSubmit="return filecheck

();">
<table border="0" cellspacing="1" class="fu_list" width="249"
height="198">
<!--    <thead>-->
<!--      <tr height=20>-->
<!--        <td colspan="2"><b>上傳文件</b></td>-->
<!--      </tr>-->
<!--    </thead>-->


<tbody>
<tr>

<td colspan="2">
<input name="file" type="file" 

class="inputbox" id="file" size=50>


</td>
</tr>
<tr>
<td colspan="2" align=center>

<input name="Submit" type="submit" value="提 

交">
    
<input name="Submit2" type="reset" value="重 

置">
<br>
<br>
<br>
</td>
</tr>
</tbody>

</table>
</form>
</body>

第二個bb.jsp頁面

<body>
<%
try{
String temp=(String)session.getId();//獲得sessionId
File f1=new File((String)request.getRealPath("photo")+"/",temp ) ;    //獲得photo所在的目

錄,並加上sessionId
out.println(f1);
FileOutputStream o=new FileOutputStream(f1);                                  //文件輸出

流指向上傳文件所在路徑
out.println(o);
InputStream in=request.getInputStream();                                         //從客戶

端獲得文件輸入流
int n;
byte b[]=new byte[10000000];//設置緩衝數組的大小
while((n=in.read(b))!=-1){
o.write(b,0,n);                                               //將數據從輸入流讀入到緩衝

數組然後再從緩衝數組寫入到文件中 
}
o.close();
in.close();                                                                               

// 關閉輸入流和文件輸出流

RandomAccessFile random=new RandomAccessFile(f1,"r");        //文件隨機讀取寫入流
int second=1;
String secondLine=null;
while(second<=2){
secondLine=random.readLine();//讀入臨時文件名
second++;
}
int position=secondLine.lastIndexOf('\\');
String filename=new String((secondLine.substring(position+1,secondLine.length()-

1)).getBytes("big5"),
"big5");

//去掉臨時文件名中的sessionId,獲得文件名,並用iso-8859-1編碼,避免出現中

文亂碼問題 
random.seek(0);
long forthEnPosition=0;
int forth=1;
while((n=random.readByte())!=1&&forth<=4){
if(n=='\n'){
forthEnPosition=random.getFilePointer();
forth++;
}//去掉臨時文件開頭的4個'\n'字符
}
File f2=new File((String)request.getRealPath("photo")+"/",filename);



//以文件的名創建另一個文件隨機讀取 
RandomAccessFile random2=new RandomAccessFile(f2,"rw");



//以文件的名創建另一個文件隨機讀取寫入流
random.seek(random.length());
long endPosition=random.getFilePointer();
int j=1;
long mark=endPosition;
while(mark<=0&&j<=6){
mark--;
random.seek(mark);
n=random.readByte();
if(n=='\n'){
endPosition=random.getFilePointer();
j++;
}                                                                                     //

去掉臨時文件末尾的6個'\n'字符 
}
random.seek(forthEnPosition);
long startPosition=random.getFilePointer();
while(startPosition<endPosition-1){
n=random.readByte();
random2.write(n);                                                  //將臨時文件去掉頭尾

後寫入到新建的文件中 
startPosition=random.getFilePointer();
}
random2.close();
random.close();
f1.delete();
%>
<script language="javascript">alert("文件上傳成功!");history.back();</script>
<%
}catch(Exception e)
{
e.printStackTrace();
out.println("上傳文件失敗!");
}
%>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章