package org.upload.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class UploadAction {
private File image;
private String imageFileName;
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String addUI(){
return "success";
}
public String execute() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//System.out.println(realpath);
if(image!=null){
File savefile = new File(new File(realpath), imageFileName);
if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "上传成功");
}
return "success";
}
}
以上是struts2.1的文件上传,在struts2.3.16中,在代码段“File savefile = new File(new File(realpath), imageFileName)”提示“The constructor File(String) is undefined.”;在代码段“if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();”提醒“The method getParentFile() is undefined for the type File.”
求教在2.3.16中如何实现文件上传。
------解决方案--------------------
action 这样配:
<action name="doUpload" class="com.example.UploadAction">
<result name="success">good_result.jsp</result>
</action>
jsp:
<s:form action="doUpload" method="post" enctype="multipart/form-data">
<s:file name="upload" label="File"/>
<s:submit/>
</s:form>
后台:
package com.example;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File file;
private String contentType;
private String filename;
public void setUpload(File file) {
this.file = file;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
public String execute() {
//...
return SUCCESS;
}
}
Good Luck~