jsp版ajax檔案上傳
jsp利用ajax + jquery無重新整理上傳圖片方法
第一步匯入需要用到的包,jquery.js,ajaxfileupload.js ,到http://www.phpletter.com去下載ajaxfileupload包
HTML代碼如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax無重新整理上傳檔案</title>
<!-- 引入相關的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:'image.do?stats=uploadImage', //需要連結到伺服器位址
secureuri:false,
fileElementId:'editorImg', //檔案選擇框的id屬性
dataType: 'text', //伺服器返回的格式,可以是json
success: function (data, status) //相當於java中try語句塊的用法
{
alert(data); //data是從伺服器返回來的值
$('#result').html('上傳圖片成功');
},
error: function (data, status, e) //相當於java中catch語句塊的用法
{
$('#result').html('上傳圖片失敗');
}
}
);
}
</script>
</head>
<body>
<form name="padd" id="padd" enctype="multipart/form-data">
<input type="file" id="editorImg" name="editorImg"/>
<input type="button" onclick="ajaxFileUpload();" value="上傳">
</form>
<div id="result"></div>
</body>
</html>
後台接收我用的是Struts自代的上傳組件進行上傳,Struts的配值就不用說了,代碼如下
//Form類
public class ProductForm extends ActionForm {
//這要與HTML頁面的file id相同
private FormFile editorImg;
public FormFile getEditorImg() {
return editorImg;
}
public void setEditorImg(FormFile editorImg) {
this.editorImg = editorImg;
}
}
//Action類
public class ProductAction extends DispatchAction{
public ActionForward uploadImage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/html;charset=GBK");
//擷取當前項目在Tomcat中的路徑
String path = request.getSession().getServletContext().getRealPath("images");
ProductForm pf = (ProductForm)form;
FormFile file = pf.getEditorImg();
FileOutputStream fos = new FileOutputStream(path + "/" + file.getFileName());
//將檔案寫入指定路徑
fos.write(file.getFileData());
fos.flush();
fos.close();
PrintWriter out = response.getWriter();
out.println(file.getFileName());
return null;
}
}