サーブレットの方が優れています。クライミングに最適なコードを共有し、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){