- Html界面代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <form method="post" action="index" enctype="multipart/form-data"> 文件:<input type="file" name="uploadImage" /><br /> <input type="submit" value="submit"> </form> </body> </html>
- 编写Action部分:
简述:
提供属性并且给出get/set方法
1.uploadImage文件
2.文件名uploadImageFileName
通过函数:FileUtils.copyFile(srcFile, destFile);达到上传目的。
package com.zhangpn.struts2; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class Helloworld { private File uploadImage; private String uploadImageFileName; public String execute() { String reslpath = ServletActionContext.getServletContext().getRealPath("/images");//获取绝对路径 if(uploadImage!=null) { File savepath = new File(new File(reslpath),uploadImageFileName);//创建保存文件信息 if(!savepath.getParentFile().exists()) { savepath.getParentFile().mkdirs(); } try { FileUtils.copyFile(uploadImage, savepath); System.out.println("upload success..."); } catch (IOException e) { e.printStackTrace(); } } return "success"; } public File getUploadImage() { return uploadImage; } public void setUploadImage(File uploadImage) { this.uploadImage = uploadImage; } public String getUploadImageFileName() { return uploadImageFileName; } public void setUploadImageFileName(String uploadImageFileName) { this.uploadImageFileName = uploadImageFileName; } }