How to upload and store image together with text field in datastore?
google app engine + java servlet
My form has text field and file field. When I upload, only image is stored
inside the datastore. Username is blank. I uses JDO. When I tried to do
video.setUsername("username" ); in the servlet. The Username field in
datastore is still blank. Any idea how to solve this issue?
Here is my jsp code.
<form method="post" enctype="multipart/form-data" action="/Upload">
Username : <input type="text" id="username" name="username"/> <br/>
<input type="file" id="uploadImg" name="uploadImg" accept="image/gif,
image/jpeg"></input>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
Here is my servlet code.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Video video = new Video();
try {
List<FileItem> items = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
video.setUsername(fieldvalue);
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
byte[] bytes = IOUtils.toByteArray(filecontent);
video.setVideo(bytes);
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
// Store the image in App Engine's datastore
pm.makePersistent(video);
} finally {
pm.close();
}
No comments:
Post a Comment