how to Upload files using MULTIPART file upload in DROPBOX - java

I am trying to upload files using MULTIPART entity method.But it fails in error says that {"error": "file parameter value 'None' is invalid"}
My code is:
File file = new File("C:/Users/sst-06/Desktop/new.txt");
service.signRequest(dropBoxToken, request);
HttpClient client = new DefaultHttpClient();
String url="https://api-content.dropbox.com/1/files/dropbox/test";
System.out.println("URL "+url);
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity( );
FileBody fileBody= new FileBody( file,"application/x-unknown");
entity.addPart( "file",fileBody);
System.out.println(fileBody);
for (String key : request.getHeaders().keySet()){
post.setHeader(key, request.getHeaders().get(key));
}
post.setEntity( entity );
String response = EntityUtils.toString( client.execute(post).getEntity(), "UTF-8" );
client.getConnectionManager().shutdown();
System.out.println(response);
And my entity file contains all the parameters as mentioned.
--hkYO-pBlK0UQLXjtVKLrBkOSXz7mYe-8WBVBvAnX
Content-Disposition: form-data; name="file"; filename="new.txt"
Content-Type: application/x-unknown
Content-Transfer-Encoding: binary
--File contents--
--hkYO-pBlK0UQLXjtVKLrBkOSXz7mYe-8WBVBvAnX--
I dont know where i felt with error.Please help.
Thanks in advance

Is there any reason why you want to use the web service directly? Will you consider using the DropBox Java SDK?
https://www.dropbox.com/static/developers/dropbox-java-sdk-1.5.3.zip

Related

Apache HttpPost Multiple Files upload failes with server error - Missing initial multi part boundary

I try to upload multiple files, using Apache Http library.
compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.6'
This is how I upload files.
String url = "url";
File f1 = new File("file1");
File f2 = new File("file2");
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "multipart/form-data");
request.addHeader("Authorization", "Basic abcd=");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody1 = new FileBody(f1, ContentType.DEFAULT_TEXT);
FileBody fileBody2 = new FileBody(f2, ContentType.DEFAULT_TEXT);
multipartEntityBuilder.addPart("file_1_param", fileBody1);
multipartEntityBuilder.addPart("file_2_param", fileBody2);
HttpEntity httpEntity = multipartEntityBuilder.build();
request.setEntity(httpEntity);
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
InputStream is = entity.getContent();
String textResponse = InputStreamUtils.readText(is);
System.out.println(textResponse);
It prints.
<pre> Server Error</pre></p><h3>Caused by:</h3><pre>java.lang.RuntimeException: javax.servlet.ServletException: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: Missing initial multi part boundary
at com.ca.devtest.acl.servlet.filters.RemoteAuthenticationFilter.doFilter(RemoteAuthenticationFilter.java:285)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
It works if I upload only one file though!
Note, this is not a duplicate. These links show posts which refer the problem on the server side. This problem is with the client side.
Jetty throws "Missing content for multipart request" on multipart form request
500 Internal server error Android HttpPost file upload
I found out a resolution. I wanted to share it with other people, so you can 1) learn how to upload files and 2) pay attention to HTTP headers.
When I append FileBody to MultipartEntityBuilder it automatically sets boundary. I simply removed this line from the code
request.addHeader("Content-Type", "multipart/form-data"); //Remove it
Example of a POST request with one or more files attached
The Multipart Content-Type
Remove the content-type option from the headers completely to make it work.
Example
headers = {
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
'postman-token': '26ef68f6-e579-a029-aec2-09b291678b4d',
'storeid': '4223556'
}

File attachment with REST API

The below code is working fine to attach file in JIRA, only one problem is here
I can't use MultipartEntityBuilder as it needed to add new dependency in pom and that is not permissible , can any one please suggest which basic API I can use there? thanks in advance
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://xxxx.zzzz.net/rest/api/2/issue/" + issueID +"/attachments");
postRequest.setHeader("Authorization", "Basic <AUTHSTRING>");
postRequest.setHeader("X-Atlassian-Token", "nocheck");
File file = new File("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
URL url = new URL("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
MultipartEntityBuilder builder = MultipartBodyBuilder.create();
// This attaches the file to the POST:
builder.addBinaryBody(
"file",
new FileInputStream(file),
ContentType.MULTIPART_FORM_DATA,
file.getName()
);
HttpEntity multipart = builder.build();
postRequest.setEntity(multipart);
HttpResponse response = httpClient.execute(postRequest);
org.apache.http.entity.mime.MultipartEntity is deprecated as a result you'll have to use MultipartEntityBuilder.
For more related post please see this thread

MultipartEntityBuilder HttpPost socket write error in java

I am trying file upload with httpPost request (by MultipartEntityBuilder) in java. But i get a Software caused connection abort: socket write error.
Here is my httpPost body (in wireShark)
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="csrf_token"
csrf:sjwzV6dOZaNFwc0jWVrNNcFvhM7uv3BK00vZ0hCgEUzi2cG7r7Arx0Q3UZKlXeaR
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="imagefilename"; filename="myfile.bin"
Content-Type: application/octet-stream
²qz‹ÁOOõMÓâg‘Ç`:----This area is file's binary code------Êëá‡/oåup
code side is:
File file = new File(filePath);
String message = csrf_token;
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("imagefilename", file, ContentType.DEFAULT_BINARY, file.getName());
builder.addTextBody("csrf_token", message, ContentType.DEFAULT_BINARY);
//
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
and error:
Is there any idea? thanks for all.
i resolved the problem, thesee links are useful for answer
here is fileupload with http Client example
here is fileupload too, with httpUrlConnection

use org.apache.http.entity.mime to upload a file to server but can't open it

I use below code to upload a text file to server and it can work.
`HttpPost httppost = new HttpPost(uri+"/uploads.xml");
MultipartEntity mpEntity = new MultipartEntity();
FileBody cbFile = new FileBody(file);
//insertValue
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
httppost.setHeader("Content-Type", "application/octet-stream");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
//execute
HttpResponse response = httpclient.execute(httppost);`
But when I download the text file from server, I could not open it and find that other messages(the bold text ) be added in the text file.
--RzBVXI2AHuDiIU5UHz-A1jZrpEg6a0JY
Content-Disposition: form-data; name="userfile"; filename="test.txt"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
CONTENT...
--RzBVXI2AHuDiIU5UHz-A1jZrpEg6a0JY--
THANKS!
Finally I resolved it.
I use this code
FileEntity entity = new FileEntity(file)
to replace:
FileBody cbFile = new FileBody(file);mpEntity.addPart("userfile", cbFile);
and it works.
But I don't know why....

Android multipart upload + blueimp UploadHandler: filetype not allowed

I'm trying to get my Android multipart image upload to work with the default blueimp PHP UploadHandler, which I'm using for the web version of my app.
It didn't work out of the box, so I experimented with the header of the requests.
I played around with it for quite a while, but since nothing worked I ended up firing up Wireshark and comparing the packets of the blueimp demo and the ones that are sent by the Android app.After some further tweaking, they look exactly the same (well the important parts):
Blueimp demo: http://i.imgur.com/T9styyR.png
Android MultipartEntity: http://i.imgur.com/OuDuyJ0.png
This is what my customized generate_response function returns:
Array
(
[0] => stdClass Object
(
[name] => 1387215600-9207
[size] => 97894
[type] => multipart/form-data; boundary=-----Don'tmindmeI'mjustaboundary
[error] => Filetype not allowed
)
)
It seems to load the whole packet instead of just it's multipart part.
Is there any way to fix that?
Here's how I create the request (not quite but these are the relevant lines):
public static String BOUNDARY = "-----Don'tmindmeI'mjustaboundary";
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, BOUNDARY, null);
File file = new File(params[2]); //params[2] contains the absolute path + filename
String filename = file.getName();
entity.addPart(filename, new FileBody(file, getMimeType(params[2]))); //getMimeType returns the MIME Type of the image e.g. image/png
HttpPost request = new HttpPost(params[0]); //params[0] contains the URL
request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
request.setEntity(entity);
HttpResponse response = client.execute(request, context);
I've been working on this for hours and it's really driving me nuts.
What am I doing wrong?
Edit:
Nevermind I got it to work
I forgot to set the name of the form to files[], which is what the UploadHandler is looking for ...
So now it looks like this:
...
public static String BOUNDARY = "-----Don'tmindmeI'mjustaboundary";
...
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, BOUNDARY, null);
File file = new File(params[2]);
String filename = file.getName();
FileBody body = new FileBody(file, getMimeType(params[2]));
FormBodyPart part = new FormBodyPart("files[]", body);
part.addField("Content-Type", getMimeType(params[2]));
part.addField("Content-Disposition", "form-data; filename=\""+filename+"\"");
entity.addPart(part);
HttpPost request = new HttpPost(params[0]);
request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
request.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
request.addHeader("Accept-Language", "en-US,en;q=0.8,de;q=0.6,es;q=0.4");
request.setEntity(entity);
HttpResponse response = client.execute(request, context);
...

Categories

Resources