【问题标题】:how to get the file size in google app engine java using apache file uploader如何使用 apache 文件上传器在 google app engine java 中获取文件大小
【发布时间】:2013-01-17 13:18:30
【问题描述】:

我正在使用下面显示的代码将一个多部分文件上传到 Google 应用引擎。在 apache commons 文件上传器的帮助下,我成功地将文件上传到 Google 应用引擎。我想验证文件大小是否为 0 字节。为此,我验证了 Google 应用引擎和 apache 公共文件上传器以检查文件大小,但我失败了。我们有什么方法可以找到文件大小。请给我一个想法。

我的 Servlet

ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter;
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
item = iter.next();
String fileName =  item.getName();
String fieldName = item.getFieldName();
if (item.isFormField()) {
String fieldValue = Streams.asString(item.openStream());
}
InputStream is1 = item.openStream();
try {
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 = is1.read(b1)) != -1) {
 writeChannel.write(ByteBuffer.wrap(b1, 0, readBytes1));
}
writeChannel.closeFinally();

【问题讨论】:

    标签: java google-app-engine jakarta-ee servlets google-cloud-storage


    【解决方案1】:

    您需要将整个is1 输入流读入一个字节缓冲区并查看它的长度。你可以使用这个sn-p:

    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    
        int len;
        byte[] data = new byte[10000];
        while ((len = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, len);
        }
    
        buffer.flush();
        return buffer.toByteArray();
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-24
      • 2010-09-10
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      相关资源
      最近更新 更多