package com.file.upload_download;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class fileUploadInterceptor extends ActionSupport {
private File file;
private String fileFileName;
private String fileContentType;
private String newFileName;
private String savePath;
public static final int BUFFERED_SIZE = 1024 * 1024;
@Override
public String execute() throws Exception {
System.out.println("上传文件类型:" + fileContentType);
System.out.println("上传文件名:" + fileFileName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
String extension = fileFileName
.substring(fileFileName.lastIndexOf("."));
newFileName = new Date().getTime() + extension;
File newFile = new File(ServletActionContext.getRequest().getRealPath(
getSavePath()), newFileName);
System.out.println("服务器中保存的路径及文件名:" + newFile.getAbsolutePath() + "/t"
+ newFile.getName());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] b = new byte[BUFFERED_SIZE];
while (bis.read(b) > 0) {
bos.write(b);
}
if (bos != null)
bos.close();
if (bis != null)
bis.close();
return SUCCESS;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getNewFileName() {
return newFileName;
}
public void setNewFileName(String newFileName) {
this.newFileName = newFileName;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
<action name="uploadfour" class="com.file.upload_download.fileUploadInterceptor">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/png,image/gif,image/jpeg</param>
<param name="maximumSize">1024</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<param name="savePath">/upLoad</param>
<result name="success">/four/showFour.jsp</result>
<result name="input">/four/indexFour.jsp</result>
</action>