我尝试使用文件服务将数据存储在Google应用引擎中,然后我成功上传了它,但后来我注意到它没有存储为blob值。所以我用Google搜索并获得了谷歌提供的这个链接How do I handle multipart form data? or How do I handle file uploads to my app?。
在本文档中,代码如下所示,
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +", name = " + item.getName());
// You now have the filename (item.getName() and the
// contents (which you can read from stream). Here we just
// print them back out to the servlet output stream, but you
// will probably want to do something more interesting (for
// example, wrap them in a Blob and commit them to the
// datastore).
这里不了解如何将它们包装为blob并将它们提交到数据存储区。任何人都可以建议我如何解决这个问题。这种方式是否将文件存储为谷歌应用引擎中的blob值?
答案 0 :(得分:1)
InputStream is = item.openStream();
try {
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mime, fileName);
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
byte[] buffer = new byte[BUFFER_SIZE];
int readBytes;
while ((readBytes = is.read(buffer)) != -1) {
writeChannel.write(ByteBuffer.wrap(buffer, 0, readBytes));
}
writeChannel.closeFinally();
String blobKey = fileService.getBlobKey(file).getKeyString();
} catch (Exception e) {
e.printStackTrace(resp.getWriter());
}