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("上传文件失败!");
}
%>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值