Uploadify跨域上傳
阿新 • • 發佈:2019-02-01
Uploadify本質上是一個基於Flash的jQuery上傳外掛.
怕忘記了,所有轉過來了
注:HTML5 寫好了,通過phonegap打包成APK後 發現檔案上傳無法使用 HTML5是相對路徑, apk裡必須是絕對路徑訪問外網伺服器的。
1、JQUERY+uploadify 實現跨域上傳
第一步 寫JS$(document).ready(function () { var historyStr = ""; var completStr = ""; var errorStr = ""; $("#file_upload").uploadify({ 'swf': 'commond-plug/uploadify/uploadify.swf', /* 'uploader': '../servlet/Upload', */ 'uploader': 'http://10.81.66.176:8080/NongGu/servlet/Upload', 'buttonText': '選擇圖片...', 'fileSizeLimit': '4000KB',//檔案最大容量 'fileTypeDesc': '圖片檔案', //檔案型別說明 'fileTypeExts': '*.gif; *.jpg; *.png',//限定可以上傳的檔案型別 /* 'fileTypeDesc' : '所有檔案', //檔案型別說明 'fileTypeExts' : '*.*',//限定可以上傳的檔案型別*/ 'formData': {'someKey': 'someValue', 'someOtherKey': 1}, //好像是可以帶引數 'height': 30, //按鈕 高度 預設30 'width': 90, //按鈕寬度 'method': 'post', //預設post 'multi': true, //支援多檔案,預設為true 'progressData': 'speed', //進度條型別,預設 percentage 'queueID': 'file_queue', //進度條 在哪裡顯示,可以不設定 'queueSizeLimit': 2, //每次提交的數量(multi =true才有意義),預設999 'removeCompleted': true,//是否在任務列表 刪除 歷史記錄 預設 true // 'removeTimeout' : 10, //不知道什麼意思 'successTimeout': 5, //預設30 'uploadLimit': 3, //一次會話中執行的上傳數量 預設999 , 'auto': false, 'onUploadStart': function (file) { $("#file_upload").uploadify("settings", "formData", {'someKey': 'zms', someOtherKey: 22}); // console.log('Attempting to upload: ' + file.name); historyStr = historyStr + "\n" + file.name; $("#history").text("歷史" + historyStr); }, 'onUploadSuccess': function (file, data, response) { $("#complet").text('檔案file.name: ' + file.name + '已經上傳成功 ,返回的資料response: ' + response + 'data:' + data); //把取回來的URI 轉碼,因為url可能包含中文,會變成亂碼。 location.href=encodeURI(encodeURI(data)); }, /* onComplete : function (event, queueID, fileObj, response, data) { alert("beyond"); completStr=completStr+"\n"+response; $("#complet").text("這裡是返回的"+completStr); },*/ onError: function (event, queueID, fileObj) { alert("檔案:" + fileObj.name + " 上傳失敗"); } });
2、 HTML 程式碼
<body> 圖片上傳2: <div id="file_queue"> <p><a href="javascript:$('#file_upload').uploadify('upload')">上傳檔案</a></p> </div> <div id="history"></div> <br> <div id="complet"></div> <br> <div id="error"></div> <input type="file" name="file_upload" id="file_upload"/> </body>
3、第二步: 修改tomcat的配置,在weapps/Root 裡增加跨域策略檔案檔案 crossdomain.xml
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-access-from domain="*" /> <allow-http-request-headers-from domain="*" headers="*"/> </cross-domain-policy>
4、java服務端的程式碼servlet
package zms.zte.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
//需要 commons-fileupload-1.2.2 commons-io-1.3.2
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
private String uploadPath = " "; // 上傳檔案的目錄
private String tempPath = " ";// 臨時檔案目錄
File tempPathFile;
private String time = "";
private String type = "";
private String xingtai = "";
private String num = "";
private String imageurl = "";
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
ServletContext s1 = this.getServletContext();
String temp = s1.getRealPath("/");
// uploadPath= request.getContextPath()+"\\files";
uploadPath = temp + "files";
System.out.println("路徑:" + uploadPath);
tempPath = uploadPath;
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 設定緩衝區大小,這裡是4k
factory.setRepository(tempPathFile);// 設定緩衝區目錄
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// 解決中文亂碼問題
upload.setHeaderEncoding("utf-8");
// Set overall request size constraint
upload.setSizeMax(41943044); // 設定最大檔案尺寸,這裡是4MB
List<FileItem> items = null;
try {
items = upload.parseRequest(request);// 得到所有的檔案
} catch (Exception ex) {
System.out.println("沒有傳檔案過來");
ex.printStackTrace();
return;
}
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
imageurl = fullFile.getName();
System.out.println("儲存檔案:" + imageurl);
// response.setContentType("text/html;charset=UTF-8");
// response.setHeader("Cache-Control", "no-cache");
// PrintWriter out = response.getWriter();
// out.write("返回內容"+fullFile.getName());
// out.flush();
// out.close();
}
else {
// 獲取引數
String fieldName = fi.getFieldName();
if (fieldName.equalsIgnoreCase("role1")) {
type = fi.getString("UTF-8");
System.out.println("型別:" + type);
}
if (fieldName.equalsIgnoreCase("mydate1")) {
time = fi.getString("UTF-8");
System.out.println("時間:" + time);
}
if (fieldName.equalsIgnoreCase("c")) {
xingtai = fi.getString("UTF-8");
System.out.println("形態:" + xingtai);
}
if (fieldName.equalsIgnoreCase("num")) {
num = fi.getString("UTF-8");
System.out.println("數量:" + num);
}
}
}
System.out.print("上傳成功");
String url = "infocz.html?time=" + time + "&type=" + type
+ "&xingtai=" + xingtai + "&imagename=" + imageurl
+ "&num=" + num;
System.out.println(url);
out.write(url);
out.flush();
out.close();
// response.sendRedirect(url);
} catch (Exception e) {
// 可以跳轉出錯頁面
System.out.println("大try出錯");
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
public void init() throws ServletException {
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}
5、html程式碼打包apk
執行的時候,後臺報錯說 ,我在安卓裡 增加了 interact-across 許可權也沒有用,看來安卓版的只能使用 phonegap 改造HTML5, 這樣 htmL5程式碼就和安卓的程式碼不一致了