文件異步上傳不能使用ajax,因爲ajax只能上傳文本信息,這裏使用uploadify。
1、在官網http://www.uploadify.com下載uploadify,它有兩個版本,Flash版本和HTML5版本,這裏我們用Flash版本,文件很小,只有49K。
2、新建文件夾uploadify,把uploadify.zip解壓到裏面(因爲其解壓出來沒有放在一個文件夾中,建議新建文件夾),然後把裝有解壓後文件的文件夾放在Webcontent目錄下。
3、在JSP頁面寫入上傳文件代碼:
<input type="file" id="personalInfoUpload"/>
使用uploadify:
<script type="text/javascript" src="<%=path%>/JS/jquery_1.7.2.js"></script><!--引入Jquery-->
<link rel="stylesheet" type="text/css" href="<%=path %>/uploadify/uploadify.css" /><!--引入uploadify樣式-->
<script type="text/javascript"
src="<%=path %>/uploadify/jquery.uploadify.js"></script><!--引入jquery.uploadify.js-->
<script type="text/javascript">
$(function() {//等同於$(document).ready(function(){});說明此函數在頁面加載完後被調用
$("#personalInfoUpload").uploadify({
buttonText: '上傳頭像',// 按鈕的顯示文本
height : 25,//按鈕高度30
swf : '<%=path%>/uploadify/uploadify.swf',//起到提交文件作用的flash
uploader : '<%=path%>/WithView/upload',//異步提交的後臺路徑(action的路徑)
width : 150,//按鈕的寬120
fileSizeLimit: '2048KB',// 上傳文件的最大限制
onUploadSuccess:function(path){//上傳成功的回調方法
}
});
});
</script>
uploadify的選項可參考:http://blog.csdn.net/wintersweetsugar/article/details/18360501
4、action方法
public class PersonalInfo {
private File filedata;// 上傳的文件(此名稱默認,如想修改請修改uploadify的fileObjName選項)
private String filedataFileName;// 上傳的文件名
private String filedataContentType;// 上傳文件類型的屬性
public File getFiledata() {
return filedata;
}
public void setFiledata(File filedata) {
this.filedata = filedata;
}
public String getFiledataFileName() {
return filedataFileName;
}
public void setFiledataFileName(String filedataFileName) {
this.filedataFileName = filedataFileName;
}
public String getFiledataContentType() {
return filedataContentType;
}
public void setFiledataContentType(String filedataContentType) {
this.filedataContentType = filedataContentType;
}
/**
* 上傳文件
* @throws IOException
*
* @since 2014-1-16
*/
public void uploadFile() throws IOException {
// 如果有文件
if (filedata != null) {
// 創建存放路徑
String filePathDir = "D:\\EclipseWorkspace\\With\\WebContent\\IMAGE"//需用雙反斜槓'\\'
//根據路徑創建文件夾對象
File importSaveFile=new File(filePathDir);
if(!importSaveFile.exists()){
importSaveFile.mkdirs();//如果目錄不存在就創建
}
//文件名+後綴
String saveFileName="唯一文件名"+"."+FilenameUtils.getExtension(filedataFileName);
File tarFile=new File(filePathDir+"//"+saveFileName);
FileUtils.copyFile(filedata, tarFile);
}
}
}
5、struts.xml配置
<package name="personalInfo" namespace="/WithView" extends="struts-default">
<action name="upload" class="com.flowers.with.controler.PersonalInfo"
method="uploadFile"></action>
</package>