ajaxFileUpload 非同步上傳檔案簡單使用,ajaxfileupload
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><!-- 引用jquery --><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script><!-- 引用ajaxfileupload.js --><script src="../js/ajaxfileupload.js"></script><script type="text/javascript">$(function(){//點擊開啟檔案選取器$("#upload").on('click', function() {$('#fileToUpload').click();});//選擇檔案之後執行上傳$('#fileToUpload').on('change', function() {$.ajaxFileUpload({url:'../FileUploadServlet',secureuri:false,fileElementId:'fileToUpload',//file標籤的iddataType: 'json',//返回資料的類型data:{name:'logan'},//一同上傳的資料success: function (data, status) {//把圖片替換var obj = jQuery.parseJSON(data);$("#upload").attr("src", "../image/"+obj.fileName);if(typeof(data.error) != 'undefined') {if(data.error != '') {alert(data.error);} else {alert(data.msg);}}},error: function (data, status, e) {alert(e);}});});});</script></head><body><!-- 點擊圖片,開啟檔案選取器,確定,上傳。(這是網路上的一個圖片) --><img id="upload" alt="" style="width: 200px; height: 200px" src="http://d.pcs.baidu.com/thumbnail/e8119cd92364a9b2714ea0a92af15aec?fid=2399642819-250528-305026848845811&time=1405674000&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-abo3xnZkLb7yMEPLDWiuaQI8kXM%3D&rt=sh&expires=2h&r=900585425&sharesign=unknown&size=c710_u500&quality=100"><!-- 隱藏file標籤 --><input id="fileToUpload" style="display: none" type="file" name="upfile"><br/> </body></html>
package com.yangshidesign.weixinface.servlet;import java.io.File;import java.io.IOException;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.alibaba.fastjson.JSONObject;/** * Servlet implementation class FileUploadServlet */@WebServlet("/FileUploadServlet")public class FileUploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.getWriter().println("ppppppppppppppppppp");}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//需要返回的fileNameString fileName = null;//參考資料 http://commons.apache.org/proper/commons-fileupload/using.html// Check that we have a file upload requestboolean isMultipart = ServletFileUpload.isMultipartContent(request);// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory();// Configure a repository (to ensure a secure temp location is used)ServletContext servletContext = this.getServletConfig().getServletContext();File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");factory.setRepository(repository);// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Parse the requesttry {List<FileItem> items = upload.parseRequest(request);for(FileItem item : items) {//其他參數String type = item.getContentType();if(type == null) {//System.out.println(item.getString(item.getFieldName()));continue;}//檔案參數fileName = item.getName();//設定儲存檔案路徑String realPath = request.getServletContext().getRealPath("/image");File dir = new File(realPath);File f = new File(dir, fileName);if(f.exists()) {f.delete();}f.createNewFile();//儲存item.write(f);}} catch (FileUploadException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}//返回結果JSONObject obj = new JSONObject();obj.put("fileName", fileName);response.getWriter().print(obj.toJSONString());}}
需要用到的一個js檔案:(點擊下載)
ajaxfileupload.js
兩個jar包:
commons-io-2.4.jar
commons-fileupload-1.3.1.jar
注意:上傳成功之後沒有執行回呼函數。
解決方案:(參考連結:http://www.myexception.cn/ajax/727453.html)
開啟ajaxfileupload.js拉到底下找到
if ( type == "json" ) { eval( "data = " + data ); }
改成:
if ( type == "json" ) { data = data.replace("<pre>","").replace("</pre>",""); //data = eval("("+data.replace("<pre>","").replace("</pre>","")+")"); }
jsp中使用jquery的ajaxfileupload外掛程式怎實現非同步上傳
頁面代碼:<html<!-- 引入相關的js檔案,相對路徑 --<script type=text/javascript src=js/jquery.js</script<script type=text/javascript src=js/ajaxfileupload.js</script<!-- 執行上傳檔案操作的函數 --<script type=text/javascriptfunction ajaxFileUpload(){$.ajaxFileUpload({url:'update.do?method=uploader', //需要連結到伺服器位址secureuri:false,fileElementId:'houseMaps', //檔案選擇框的id屬性dataType: 'xml', //伺服器返回的格式,可以是jsonsuccess: 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;whi......餘下全文>>
jsp中使用jquery的ajaxfileupload外掛程式怎實現非同步上傳
<script type=text/javascript src=js/jquery.js</script<script type=text/javascript src=js/ajaxfileupload.js</script<!-- 執行上傳檔案操作的函數 --<script type=text/javascriptfunction ajaxFileUpload(){$.ajaxFileUpload({url:'update.do?method=uploader', //需要連結到伺服器位址secureuri:false,fileElementId:'houseMaps', //檔案選擇框的id屬性dataType: 'xml', //伺服器返回的格式,可以是jsonsuccess: 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(......餘下全文>>