在做文件上传时,不加限制上传任意类型文件都成功,但是如果加了“allowedTypes”限制文件类型后,上传正确类型成功,上传错误类型失败,这些都是理所当然的结果。问题是上传错误类型失败后,再上传正确的文件,也跳转到input视图,不经过action。如限制只能上传gif格式文件,第一次上传gif图片返回success;第二次上传非gif文件,返回input;第三次上传gif文件,还是返回input,怎么解决?
代码如下:
jsp页面:
action:
package ss2h.Action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 572146812454l ;
private static final int BUFFER_SIZE = 16 * 1024 ;
private File myFile;
private String contentType;
private String fileName;
private String imageFileName;
private String caption;
public void setMyFileContentType(String contentType) {
this .contentType = contentType;
}
public void setMyFileFileName(String fileName) {
this .fileName = fileName;
}
public void setMyFile(File myFile) {
this .myFile = myFile;
}
public String getImageFileName() {
return imageFileName;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this .caption = caption;
}
private static void copy(File src, File dst) {
try {
InputStream in = null ;
OutputStream out = null ;
try {
if (dst.getParentFile() != null
&& dst.getParentFile().exists() == false) {
if (dst.getParentFile().mkdirs() == false) {
throw new IOException("Destination '" + dst
+ "' directory cannot be created");
}
}
//文件不会自动保存到服务器,必须通过流操作
in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
byte [] buffer = new byte [BUFFER_SIZE];
while (in.read(buffer) > 0 ) {
out.write(buffer);
}
} finally {
if ( null != in) {
in.close();
}
if ( null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
@Override
public String execute() {
imageFileName = new Date().getTime() + getExtention(fileName);
File imageFile = new File(ServletActionContext.getServletContext().getRealPath( "/UploadImages" ) + "/" + imageFileName);
copy(myFile, imageFile);
System.out.println("haha");
return SUCCESS;
}
}
struts.xml:
<!-- 验证上传文件的类型 -->
image/gif
/fail.jsp
/success.jsp
applicationContext.xml:
web.xml:
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2
/*
struts-cleanup
org.apache.struts2.dispatcher.ActionContextCleanUp
struts-cleanup
/*
org.springframework.web.context.ContextLoaderListener