我正在尝试使用 Apache File Upload 存储文件。我的 JSP 如下所示,
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit"value="upload" />
</form>
在我的 Servlet 中,我可以获得如下上传的文件,
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mime,fileName);
boolean lock = true;
byte[] b1 = new byte[BUFFER_SIZE];
int readBytes1 = is.read(b1, 0, BUFFER_SIZE);
while (readBytes1 != -1) {
writeChannel.write(ByteBuffer.wrap(b1, 0, BUFFER_SIZE));}
writeChannel.closeFinally();
现在我尝试使用以下代码将文件存储为 blob 值,
String blobKey = fileService.getBlobKey(file).getKeyString();
Entity Input = new Entity("Input");
Input.setProperty("Input File", blobKey);
datastore.put(Input);
当我尝试这个时,我可以存储文件名 blob 键,但文件没有存储。它在 Google App 引擎的 Blob 查看器和 Blob 列表中显示“0”字节。
请给我一个解决这个问题的想法,
感谢您的帮助。
我的小服务程序
public class UploadServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static int BUFFER_SIZE =1024 * 1024* 10;
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter;
try {
iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String fileName = item.getName();
String mime = item.getContentType();
InputStream is = new BufferedInputStream(item.openStream());
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if( !isMultipart ) {
resp.getWriter().println("File cannot be uploaded !");}
else {
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mime,fileName);
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
byte[] b1 = new byte[BUFFER_SIZE];
int readBytes1;
while ((readBytes1 = is.read(b1)) != -1) {
writeChannel.write(ByteBuffer.wrap(b1, 0, readBytes1));}
writeChannel.closeFinally();
String blobKey = fileService.getBlobKey(file).getKeyString();
Entity Input = new Entity("Input");
Input.setProperty("Input File", blobKey);
datastore.put(Input);}}
catch (Exception e) {
e.printStackTrace(resp.getWriter());}
}
}