Struts 2的文件上传功能,默认基于Common- FileUpload 实现
上传表单页面
|
struts.xml配置文件
|
接收上传请求的Action
- public class FileUploadAction extends ActionSupport {
- // 上传文件对象,该属性必须符合特定规范,即与表单提交name相同
- private File file;
- // 上传文件的MIME类型
- private String fileContentType;
- // 上传文件的文件名
- private String fileFileName;
- // 上传至指定路径,该参数值由struts.xml配置
- private String uploadPath;
- public String upload() throws Exception {
- OutputStream os = null;
- InputStream is = null;
- try {
- os = new FileOutputStream(uploadPath+fileFileName);
- is = new FileInputStream(file);
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = is.read(buffer)) != -1) {
- os.write(buffer, 0, len);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- if(os!=null)
- os.close();
- if(is!=null)
- is.close();
- if(file!=null)
- is.close();
- }
- return SUCCESS;
- }
- }