用struts2框架编写单个文件上传和多个文件上传的例子,
此处用的是ajax单个文件上传,该用到插件ajaxFileupload的js文件。
index.jsp
<!--所需的JS文件-->
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/ajaxfileupload.js"></script>
<img src="loading.gif" id="diLoading" />-->
<input type="file" id="file" name="file" />
<input type="button" value="上传" οnclick="return ajaxFileUpload();" />
js文件
function ajaxFileUpload()
{
$("#loading")
.ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来
后台fileuploadAction代码
public class FileAction extends ActionSupport {
private File file;
private String fileFileName;
private String fileFileContentType;
private String message = "你已成功上传图片!";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
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 getFileFileContentType() {
return fileFileContentType;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
@SuppressWarnings("deprecation")
@Override
public String execute() throws Exception {
String path = ServletActionContext.getRequest().getRealPath("/upload");
System.out.println(path + "/"+ this.getFileFileName());
FileUtils.createParentDir(path);
try {
File f = this.getFile();
System.out.println(f.getPath());
if(this.getFileFileName().endsWith(".exe")){
message="对不起,你上传的文件格式不允许!!!";
return ERROR;
}
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getFileFileName());
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
message = "对不起,图片上传失败了!!!";
}
return SUCCESS;
}
}
struts.xml的配置
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.encoding" value="utf-8" />
<constant name="struts.devMode" value="false"/>
<constant name="struts.multipart.maxSize" value="20971520"/>
<package name="struts2" extends="json-default">
<action name="fileUploadAction" class="org.action.FileAction">
<result type="json" name="success">
<param name="contentType">
text/html
</param>
</result>
<result type="json" name="error">
<param name="contentType">
text/html
</param>
</result>
</action>
</package>