一.sample.html(提交页面)
<form name="upfile_form" action="singertonUploadAction" method="POST" enctype="multipart/form-data">
<input type="file" name="upload_file" id="upload_file" onchange="checkFileSize(this);" />
<p>
<input type="submit" value="submit" />
</p>
<iframe name="check_file_frame" style="display:none;"></iframe>
</form>
二.
public class SingertonUploadForm extends ActionForm {
private FormFile upload_file;
public FormFile getUpload_file() {
return upload_file;
}
public void setUpload_file(FormFile upload_file) {
this.upload_file = upload_file;
}
}
三.
public class SingertonUploadAction extends Action {
private static String UPLOAD_FILE_PATH = "c:/";
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
SingertonUploadForm uploadForm = (SingertonUploadForm)form;
//得到上传的文件
FormFile uploadFile = uploadForm.getUpload_file();
//得到文件名
String fileName = uploadFile.getFileName();
//得到文件大小
int fileSize = uploadFile.getFileSize();
System.out.println("FileName = " + fileName);
System.out.println("FileSize=" + fileSize);
boolean result = true;
try{
//得到文件的输入流
InputStream is = uploadFile.getInputStream();
//上传文件
uploadFile(fileName,is);
}catch(IOException ex){
ex.printStackTrace();
//假如上传文件失败,设置一个失败的标记位
result = false;
}
if(result){
return mapping.findForward("success");
} else {
return mapping.findForward("fail");
}
}
/**
* 上传文件
* @param fileName
* @param is
* @throws IOException
*/
private void uploadFile(String fileName,InputStream is) throws IOException{
OutputStream os = new FileOutputStream(UPLOAD_FILE_PATH + fileName);
//8k缓存数据
byte[] buffer = new byte[1024 * 8];
//设置读进缓存的字节数
int len;
while((len=is.read(buffer))!=-1){
//将缓存数据写入磁盘
os.write(buffer,0,len);
}
//关闭输出流
os.close();
//关闭输入流
is.close();
}
}
四.类似ajax提交需要check_file.js
var fileForm = new Object();
function checkFileSize(fileObj) {
if(fileObj.value != "") {
var form = document.forms['upfile_form'];
//把form的原始数据缓存起来
fileForm.f = form;
fileForm.a = form.getAttribute("action"); //form.action 为一个静态的对象,所以这里要使用getAttribute方法取值
fileForm.t = form.target;
//请求服务器端
form.target = "check_file_frame";
//form.action = "./ajax.php?act=upload";
form.action = "singertonUploadAction.do";
//form.submit(); 其实上面的action已经会执行submit操作,这步可有可无
}
return false;
}
function ajax_callback(result) {
//还原form属性
fileForm.f.target = fileForm.t;
fileForm.f.setAttribute("action", fileForm.a);
//处理结果
switch(result) {
case 0:
alert("文件超过了200K或者没有选择文件,请重新上传!");
//todo somthing
default :
alert("合法");
//do somthing,如果你想使用这种方法实现真正的上传的话,那么在成功后把返回的文件路经存储在一个 input[hidden]里是个不错的办法
}
return ;
}