jsp页面
form中的enctype属性应设置为:multipart/form-data
<form action="/uplode.do" method="post" enctype="multipart/form-data">
<td> <input type="file" id="file" name="file" value="file" onchange="fz();"/> <input type="hidden" id="filepath" name="attachment.filepath" value="$attachment.filepath"/> <input type="hidden" id="filename" name="attachment.filename" value="$attachment.filename"/> <input type="hidden" id="suffix" name="attachment.suffix" value="$attachment.suffix"/> </td>
</form>
function fz(){ var aa=document.getElementById("file").value; var arrS2=aa.split("\"); var i=arrS2.length; var filename = arrS2[i-1] var arrb = aa.split("."); var j = arrb.length; document.getElementById("file").value=aa; document.getElementById("filename").value=filename; document.getElementById("filepath").value="/uploadfiles/casus/"+filename; document.getElementById("suffix").value=arrb[j-1]; }
action:
//附件相关 private AttachmentMatters attachment; private String fileName; //名字 private String suffix; //后缀 private String file; private String attachmentid;
/** * 上传 */ public void uploadFile(){ try{ String name = attachment.getFilename(); upload(this.file,name) ; //上传到服务器
//保存到附件表里
if(name!=null&&!name.equals("")){ attachment.setFilepath("uploadfiles/sss/"+name); attachment.setUploadDate(new Date()); bean.saveObject(attachment); } }catch(Exception e){ e.printStackTrace(); } }
public static void upload(String file, String name){ if(file !=null){ FileOutputStream outputStream; try { String path=ServletActionContext.getRequest().getRealPath("/uploadfiles/matters"); String path1=path; path1.replaceAll("\u002E\u002E", "2"); String fileDir = path+File.separator; String filePath=fileDir+name; File f=new File(fileDir); f.mkdirs(); outputStream = new FileOutputStream(filePath); FileInputStream fileIn = new FileInputStream(file); byte[] buffer = new byte[128]; int len; while ((len = fileIn.read(buffer))>0){ outputStream.write(buffer, 0, len); } fileIn.close(); outputStream.close(); }catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("文件为空"); } }