Reputation: 11
The problem with the code I use is that the file appears in the blob, but as a 0B size file. As if no data was written to the blob.
This is the form I use in my 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>
And I have the following code in my 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) {
}
Upvotes: 1
Views: 1482
Reputation: 7438
I don't know the equivalent syntax in Java, but in C# you often have to reset your position in the stream back to 0 before passing it to the blob upload method (this is usually the case if the stream has already been read - which it would have for you to get the length). Something like
is.position = 0;
blob.upload(is, fileReference.length());
Upvotes: 3