今天要做一個圖片異步上傳的功能,需求是這樣的
在官網讓玩家提出問題反饋,只是再發聵是需要玩家上傳圖片作爲客服審覈的證據。爲了保證官網的安全性,於是準備了一臺圖片服務器,專門存儲圖片。
我的思路是在頁面上傳文件到圖片服務器,並返回圖片的地址。然後再提交表單時,將圖片url,保存入數據庫。
1. 利用 ajaxfileupload進行上傳時,是不能進行跨域操作的。
2. 所以更換爲jquery.fileupload進行跨域操作,不過沒有中文文檔,使用時很是費勁。因爲第一次上傳沒有反應,只有第二次的時候纔會成功,讓人很頭疼。我對js又不是很熟,所以準備暫且放置一下。用我比較熟的服務器端的開發來完成。
3. 在本本服上傳文件和信息。然後利用httpclient 向圖片服務器發送請求進行保存。這個流程比較好控制。
下面是httpclient的代碼
public static void main(String[] args) throws ClientProtocolException,
IOException {
HttpClient httpclient = new DefaultHttpClient();
// 請求處理頁面
HttpPost httppost = new HttpPost(
"http://localhost:8080/LogTest/test/upload");
// 創建待處理的文件
FileBody file = new FileBody(new File(
"E:\\worktools\\resin-pro-3.1.13\\conf\\resin.conf"));
// 創建待處理的表單域內容文本
StringBody descript = new StringBody("0431.la");
// 對請求的表單域進行填充
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("fileName", file);
reqEntity.addPart("descript", descript);
// 設置請求
httppost.setEntity(reqEntity);
// 執行
HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
// System.out.println(response.getStatusLine());
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
// 顯示內容
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
if (entity != null) {
entity.consumeContent();
}
}
}
明天會將jquery.fileupload的代碼優化以後,再將該js代碼上傳。