Java上传文件(简单例子)
jsp页面:
<%--有附件的话:要设置enctype属性;--%>
<html:formaction="submitPublishReply.do"method="POST"onsubmit="returncheck();"enctype="multipart/form-data">
附件:<inputtype="file"name="attach"/>
<inputtype="submit"value="回复"/>
</ul>
</html:form>
ActionForm:
privateFormFilefile;
Action:
importorg.apache.commons.fileupload.*;
importorg.apache.commons.fileupload.disk.*;
importorg.apache.commons.fileupload.servlet.*;
importjava.io.PrintWriter;
importjava.io.File;
importorg.apache.struts.upload.FormFile;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.FileOutputStream;
//附件
FormFilefile=(FormFile)replyForm.getFile();
if(file!=null&&file.getFileName().trim().length()>0){
StringfileName=file.getFileName();
byte[]b=file.getFileData();
Stringdir=request.getRealPath("/uploadfile");//request.getRealPath获得web应用程序在服务器的绝对路径
OutputStreamstreamOut=newFileOutputStream(dir+"/"+
fileName);
streamOut.write(b,0,b.length);
}