如何将图像上传到Azure中的blob?

时间:2013-10-09 16:50:10

标签: java file-upload azure azure-storage-blobs apache-commons-fileupload

我使用的代码的问题是该文件出现在blob中,但是作为0B大小的文件。好像没有数据写入blob。

这是我在JSP中使用的表单:

<form method="POST" action="UploadServlet" enctype="multipart/form-data" >
    <input type="file" name="file" id="file" /> <br/>
    </br>
    <input type="submit" value="Upload" name="upload" id="upload" />
</form>

我的servlet中有以下代码:

    try {
                CloudStorageAccount account;
                CloudBlobClient serviceClient;
                CloudBlobContainer container;
                CloudBlockBlob blob;

                account = CloudStorageAccount.parse(storageConnectionString);
                serviceClient = account.createCloudBlobClient();
                container = serviceClient.getContainerReference("gettingstarted");
                container.createIfNotExist();

                // Set anonymous access on the container.
                BlobContainerPermissions containerPermissions;
                containerPermissions = new BlobContainerPermissions();
                                   containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
                container.uploadPermissions(containerPermissions);

                FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload fileUpload = new ServletFileUpload(factory);

                //process only if its multipart content
                InputStream is = null;
                if (ServletFileUpload.isMultipartContent(request)) {
                    List items = fileUpload.parseRequest(request);
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (!item.isFormField()) {
                            is = item.getInputStream();
                            String name = new File(item.getName()).getName();
                            System.out.println(name);
                            blob = container.getBlockBlobReference(name);
                            File fileReference = new File(item.getName());
                            System.out.println(is);
                            blob.upload(is, fileReference.length());
                        }
                    }
                }
                is.close();

                request.getRequestDispatcher("hello").forward(request, response);

    } catch (Exeption e) {
    }

1 个答案:

答案 0 :(得分:3)

我不知道Java中的等效语法,但是在C#中,您经常需要将流中的位置重置为0,然后再将其传递给blob upload方法(如果流已经存在,通常就是这种情况)阅读 - 它可以让你获得长度)。 像

这样的东西
is.position = 0;
blob.upload(is, fileReference.length());