是用一個servlet更好,我將分享代碼完全適用於登山和的BlobKey必須在數據存儲中捕獲和存儲
.JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="com.google.appengine.api.blobstore.BlobstoreServiceFactory" %>
<%@ page import="com.google.appengine.api.blobstore.BlobstoreService" %>
<%
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String url = blobstoreService.createUploadUrl("/upload");
%>
<!DOCTYPE html>
<html lang="en">
<body>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Foto</label>
<div class="col-lg-10">
<input id="file-foto-usuario" type="file" name="file-foto-usuario" onchange="UploadImage()">
<input type="hidden" class="form-control" id="foto-usuario" placeholder="Foto">
</div>
</div>
</body>
的.js
function UploadImage(){
var inputFileImage = document.getElementById("file-foto-usuario");
var file = inputFileImage.files[0];
var data = new FormData();
data.append("file-foto-usuario",file);
var url = "<%=url%>";
$.ajax({
url: url,
type: 'POST',
cache : false,
data : data,
processData : false,
contentType : false,
dataType: "json",
success: function (response) {
if(response.success){
alert(response.blobKey);
}else{
alert("fail");
}
}
});
}
Upload.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
public class UploadServlet extends HttpServlet {
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
JSONObject finalJson = new JSONObject();
Boolean success= false;
String blobid= "";
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobKey = blobs.get("file-foto-usuario");
if (blobKey == null) {
resp.sendRedirect("/");
} else {
success= true;
blobid= blobKey.getKeyString();
//resp.sendRedirect("/serve?blob-key=" + blobKey.getKeyString());
}
finalJson.put("success", success);
finalJson.put("blobKey", blobid);
resp.setCharacterEncoding("utf8");
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.print(finalJson);
}
}
獲取URL圖像
String urlFoto = "";
BlobKey blobKey = new BlobKey(Blobkey);
ImagesService imagesService = ImagesServiceFactory.getImagesService();
try{
urlFoto = imagesService.getServingUrl(blobKey, true);
}catch (IllegalArgumentException ie){
你到底想幹什麼?如果您嘗試從您的應用程序寫入blobstore,則應使用新的寫入API。 – 2011-05-15 22:32:25