Upload file with Java servlet to Google App Engine
I would like to be able to have the user upload short audio samples to my App Engine application and store them in the provided Datastore. I'm using t开发者_开发技巧he Java servlet version.
My problem is using a multi-part form to upload a file. Using the normal request.getParameter()
method returns null with multi-part forms. I have read about using the oriely MultiPartForm class, but that seems to involve saving the file to the server filesystem, which is out of the question.
Can somebody show me how to upload a file so that it ends up in an App Engine database Blob object?
You can do it this way: example
<input id="file-pdf" type="file" name="file-pdf">
<button id="submit-pdf">submit</button>
javascripts
$("#submit-pdf").click(function() {
var inputFileImage = document.getElementById("file-pdf");
var file = inputFileImage.files[0];
var data = new FormData();
data.append("file-pdf",file);
$.ajax({
url: "uploadpdf",
type: 'POST',
cache : false,
data : data,
processData : false,
contentType : false,
dataType: "json",
success: function (response) {
if(response.success){
console.log("ok");
}else{
console.log("fail");
}
}
});
});
and servlet
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
JSONObject finalJson = new JSONObject();
Boolean success = false;
String ajaxUpdateResult = "";
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
logger.warning("Got a form field: " + item.getFieldName()+ "value="+ item.getName());
String idForm= item.getFieldName();
} else {
logger.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName()+ " content="+item.getContentType() + " header="+item.getHeaders());
// here save
//success = insertFile(String title,String mimeType, String filename, InputStream stream);
}
}
} catch (Exception ex) {
}
finalJson.put("success", success);
resp.setCharacterEncoding("utf8");
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.print(finalJson);
}
精彩评论