先看简单的jsp页面
<form action="fileupload.action" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" />
</form>
<img alt="" src="image/${img }">
再看,struts.xml的设置。
<package name="default" namespace="/" extends="struts-default">
<action name="fileupload" class="actions.UploadAction">
<result name="success">/index.jsp</result>
<result name="error">/failture.jsp</result>
</action>
</package>
action的代码。
package actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
// 上传文件属性,与form表单提交过来的name属性一样。
private File image;
// 上传文件名
private String imageFileName;
// 上传文件属性
private String imageContentType;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
/**
*
* @return
*/
public String execute() throws Exception {
String path = ServletActionContext.getServletContext().getRealPath("image")+ File.separator + imageFileName;
System.out.println(path);
FileInputStream is = new FileInputStream(image);
FileOutputStream os = new FileOutputStream(path);
byte[] by = new byte[is.available()];
is.read(by);
os.write(by);
is.close();
os.flush();
os.close();
ServletActionContext.getServletContext().setAttribute("img",imageFileName);
return SUCCESS;
}
}
注意了:报
Unable to find 'struts.multipart.saveDir'
可能的原因上传文件名写错,或者没有封装get/set.
改进上面读写代码:
FileInputStream is = new FileInputStream(image);
FileOutputStream os = new FileOutputStream(path);
byte [] by=new byte[is.available()];
while (is.read(by) >0) {
os.write(by);
}
is.close();
os.flush();
os.close();
继续改进:
FileUtils.copyFile(image, new File(path));
还有注意的是:使用前两种办法上传时,建议现在WebRoot下面创建一个文件夹,上面例子中我创建的文件夹的名字就在这里:getRealPath(“image”)。
本文介绍了如何使用Struts2框架实现文件上传功能,包括JSP页面设置、struts.xml配置及Action处理逻辑。通过具体代码示例展示了上传过程中的注意事项。

被折叠的 条评论
为什么被折叠?



