頁面代碼:
<html>
<!-- 引入相關的js檔案,相對路徑 -->
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<!-- 執行上傳檔案操作的函數 -->
<script type="text/javascript">
function ajaxFileUpload(){
$.ajaxFileUpload(
{
url:'update.do?method=uploader', //需要連結到伺服器位址
secureuri:false,
fileElementId:'houseMaps', //檔案選擇框的id屬性
dataType: 'xml', //伺服器返回的格式,可以是json
success: function (data, status) //相當於java中try語句塊的用法
{
$('#result').html('添加成功');
},
error: function (data, status, e) //相當於java中catch語句塊的用法
{
$('#result').html('添加失敗');
}
}
);
}
</script>
</head>
<body>
<form method="post" action="update.do?method=uploader" enctype="multipart/form-data">
<input type="file" id="houseMaps" name="houseMaps"/>
<input type="button" value="提交" onclick="ajaxFileUpload()"/>
</form>
<div id="result"></div>
</body>
</html>
伺服器代碼:
public class UpdateAction extends DispatchAction {
public ActionForward uploader(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UpFormForm upFormForm = (UpFormForm) form;
FormFile ff = upFormForm.getHouseMaps();
try {
InputStream is = ff.getInputStream();
File file = new File("D:/" + ff.getFileName()); //指定檔案儲存體的路徑和檔案名稱
OutputStream os = new FileOutputStream(file);
byte[] b = new byte[1024];
int len = 0;
while((len = is.read(b)) != -1){
os.write(b, 0, len);
}
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}