今天看了struts2权威指南 第六章上传文件
发现在上传gif或html等文件时候
action中的
uploadFileName
uploadContentType
是可以显示出来的。
一旦上传doc.xls.,ppt等就显示为null
不知道怎么解决,谢谢大家帮忙.
以下是struts2 配置
image/*,text/*,application/msword,application/ms-excel
/files
/succ.jsp
/file.jsp
以下是action
package struts2.test.action;
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.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private File upload;
private String uploadContentType;
private String savePath;
private String uploadFileName;
private String allowTypes;
@SuppressWarnings("deprecation")
public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = upload.getName();
}
public String execute() throws IOException{
String filterResult = filterType(getAllowTypes().split(","));
if(filterResult != null){
ActionContext.getContext().put("typeError", "您要上传的文件类型不正确");
return filterResult;
}else{
FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer))>0){
fos.write(buffer,0,len);
}
fos.close();
fis.close();
return SUCCESS;
}
}
public String getAllowTypes() {
return allowTypes;
}
public void setAllowTypes(String allowTypes) {
this.allowTypes = allowTypes;
}
public String filterType(String[] types){
System.out.println(getUploadContentType());
String fileType = getUploadContentType();
for(String type:types){
if(type.equals(fileType)){
return null;
}
}
return INPUT;
}
}
jsp 页面
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@taglib prefix="s" uri ="/struts-tags"%>
文件上传
${typeError}