用struts2上传文件
在jsp页面:在form表单中一定要加上enctype="multipart/form-data"
???? 上传文件:<input type="file" name="upload"/>?
? 在action页面:
? ?private File upload;
??private String uploadContentType;//文件类型注意此名的前半部分一定要和jsp中的file 的name一样
??private String uploadFileName;
??private String uploadSavepath="\\upload\\exam";?
??public String getUploadSavepath() {
??return ServletActionContext.getServletContext().getRealPath(this.uploadSavepath);
??}
??public void setUpload(File upload) {
???this.upload = upload;
??}
??public void setUploadContentType(String uploadContentType) {
???this.uploadContentType = uploadContentType;
??}
??public void setUploadFileName(String uploadFileName) {
???this.uploadFileName = uploadFileName;
??}
??
??public String uploadfile(){
?? if(this.upload != null){
????SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
????String date = dateFormat.format(new Date());
????int simple = new Random().nextInt(1000);
????this.filename = date + simple + this.uploadFileName.substring(this.uploadFileName.indexOf("."));
????String bookAllName = this.getUploadSavepath() + File.separator + filename;
????File? file = new File(bookAllName);
????this.upload.renameTo(file);
???}
?? return "uploadfile";
? }
? ok了!