david
david

Reputation: 2142

AppEngine - Send files to the blobstore using HTTP

I'm trying to send files to the blobstore using http requests.

First I made a button to call the createUploadUrl to get the upload url.

Then I made a client:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL_FROM_CREATEUPLOADURL);

httpPost.setEntity(new StringEntity("value1"));
HttpResponse httpResponse = httpClient.execute(httpPost);

But I have 2 problems:

What I'm doing wrong?

Upvotes: 4

Views: 2613

Answers (2)

david
david

Reputation: 2142

apparently the entity must be a MultiPartEntity.

This is the client code to get the URL:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myDomain/mayServlet);
HttpResponse httpResponse = httpClient.execute(httpPost);
Header[] headers = httpResponse.getHeaders(myHeader);
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
if(header.getName().equals(myHeader))
uploadUrl = header.getValue();

This is the server code to return the URL:

BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadUrl = blobstoreService.createUploadUrl(requestHandlerServlet);
resp.addHeader("uploadUrl", uploadUrl);

This is the client upload code:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uploadUrl);
MultipartEntity httpEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(new File("filePath/fileName"));
httpEntity.addPart("fileKey", contentBody);
httpPost.setEntity(httpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);

so easy... :(

Upvotes: 5

Nick Johnson
Nick Johnson

Reputation: 101139

It sounds like you're trying to hard-code a single upload URL. You can't do that - you need to generate a new one for each file you want to upload.

You also need to make sure that you upload the file as a multipart message rather than using formencoding or a raw body. I'm not familiar with the Java APIs, but it looks like you're setting the raw body of the request.

Upvotes: 5

Related Questions