uploading png to server with java using POST data - java

Hi ive been having some trouble trying to transfer a png image to my webserver using java and php Ive tried using FTP but the software that Im scripting for blocks port 21 rendering it useless
I was directed to use form urlencoded data then use a POST request to get it
im completely lost on this topic and could just use some direction apparently file and image hosting sites use the same method to transfer files and images from the users computer to their servers.
maybe just an explanation of whats going on might help so that I can grasp what exactly im trying to do with java and php
Any help would be much appreciated!

I've also been facing the same kind of problem a short time ago.
After some researches, I found out that the HttpComponents library from Apache (http://hc.apache.org/) contains pretty much everything you'll need to build HTTP-POST request in a quite simple way.
Here is a method that will send a POST request with a file to a certain URL:
public static void upload(URL url, File file) throws IOException, URISyntaxException {
HttpClient client = new DefaultHttpClient(); //The client object which will do the upload
HttpPost httpPost = new HttpPost(url.toURI()); //The POST request to send
FileBody fileB = new FileBody(file);
MultipartEntity request = new MultipartEntity(); //The HTTP entity which will holds the different body parts, here the file
request.addPart("file", fileB);
httpPost.setEntity(request);
HttpResponse response = client.execute(httpPost); //Once the upload is complete (successful or not), the client will return a response given by the server
if(response.getStatusLine().getStatusCode()==200) { //If the code contained in this response equals 200, then the upload is successful (and ready to be processed by the php code)
System.out.println("Upload successful !");
}
}
In order to complete the upload, you must have a php code that handle that POST request,
here it is:
<?php
$directory = 'Set here the directory you want the file to be uploaded to';
$filename = basename($_FILES['file']['name']);
if(strrchr($_FILES['file']['name'], '.')=='.png') {//Check if the actual file extension is PNG, otherwise this could lead to a big security breach
if(move_uploaded_file($_FILES['file']['tmp_name'], $directory. $filename)) { //The file is transfered from its temp directory to the directory we want, and the function returns TRUE if successfull
//Do what you want, SQL insert, logs, etc
}
}
?>
The URL object given to the Java method must point to the php code, like http://mysite.com/upload.php and can be build very simply from a String. The file can also be build from a String representing its path.
I didn't take the time to test it properly, but it was build upon proper working solution, so I hope this will help you.

Related

Getting a PDF from another API

How can I get a PDF from another API through my own API then to the front for downloading by the user.
All I get now is a blank page.
The back is in Scala and when I println the file, I get it in a String.
In the front, I get the blob and use that function to download it :
onDownload(invoice) {
var mediaType = 'application/pdf';
this.invoices.downloadInvoice(invoice.id).subscribe((file: Blob) => {
const fileName = invoice.number;
var blob = new Blob([file], { type: mediaType });
const fileUrl = URL.createObjectURL(blob);
FileSaver.default(fileUrl, fileName.toString());
}), err => {
console.error(err);
}
}
The back is using Play and the WebService to get the file from another API but I can only receive it as a string it seems. Should I try to store him on the server then serve it to the front ?
Which scala-server used? And what does the path/API return?
Should I try to store him on the server then serve it to the front
This is the sure-shot way of making it work. For eg: If using akka-server, save the incoming file in some temporary location (say /tmp), and use akka-route getFromFile to server the file to front-end. Every server will have an equivalent of this.
If we want to bypass file-saving, we need to trick/hack the client into thinking that the incoming string is actually a file. I am not sure if your server will allow this, but you can try by passing the same http-headers. For this, create a simple API to send some PDF, check all the headers received on the client side, and then make sure your hacky way sends the same http-headers.

Upload chunked video to Twitter with spring-social-twitter / postman

I am currently trying to build an application to post videos to Twitter on behalf of a user.
So I currently have the application-key, application-secret, access-token and access-secret.
final TwitterTemplate twitterTemplate = new TwitterTemplate(
"application-key",
"application-secret",
"access-token",
"access-secret");
So using this I can actually post a tweet containing only text.
If I want to include an image I have to include the workaround "solution" posted on a bug of spring-social-twitter. This resolves the image but the video still cannot be uploaded.
So the rational thinking was to try out this upload with postman to "isolate" the call itself.
In the previous image we can see the Authorization process. This is the same for Every single call I make.
with this Auth a simple POST to https://api.twitter.com/1.1/statuses/update.json?status=hello works. Same with 2 calls for image.
POST to https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image for the image upload ( body -> media : image ).
POST to https://api.twitter.com/1.1/statuses/update.json merge the media_id with a new tweet.
But back to the video following again the official guide of twitter when I send this
the response is
when the request media_type does not contain / then a valid response will return from tweeter with a media_id, lets call it X.
So I append a video ( second command ) on X and then finalize the video ( third command ) on X. But as expected the response is
as the media_type was never provided. On the other hand if the video on the second step is pushed as base64 encoded ( and including the header for base64 encoding) then a response of
No matter what I have done so far I cannot make it post a video. I even used Postman as a proxy for twurl and captured the request of twurl that did upload the video. Changed the auth with mine ( because of nonce it requires to be recreated ) and the request failed to upload the video!
some notes :
the credentials are up to dates and work from twurl.
the video is valid and can be uploaded from both tweeter ui and twurl upload command.
the base64 convert was encoded / decoded with linux base64 tool piped to file and validated that the size is the same.
If any other clarification is required please let me know!
Thank you in advance
I know it's late but in case someone has same question,
to upload video on twitter you have to use chunked-media-upload method.
here's the reference
https://developer.twitter.com/en/docs/media/upload-media/uploading-media/chunked-media-upload

Upload image from android app gallery to local spring server

Last 3 days I started to learn Spring. I want to send a image from the phone gallery to the spring server. I want to mention that the server is local so I'm using localhost. I saw a tutorial that if I want to send stuff to a local server, the server address is my laptop address + the port (ex. 8080) and I have to connect the phone to the same Wi-Fi as the laptop.
I know how to get the image from the gallery but I don't know how to send it. Many solutions from stackoverflow are old and some classes got deprecated and I can't try their method.
Also, what should I do in the spring controller to receive the image?
You'll have use MultipartFile to upload an image using spring. Please go through following example.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String fileUpload(#RequestParam("file") MultipartFile file) {
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
//save file in server - you may need an another scenario
Path path = Paths.get("/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
//redirect to an another url end point
return "redirect:/upload-status";
}
Please make sure you can reach to your computer through your mobile device. I believe you may know that Android requires additional privilege to use network connections. So make sure you have permitted your app to access network.
EDIT:
You can use HttpClient to upload file from your mobile app. Please try following code.
HttpClient httpClient = AndroidHttpClient.newInstance("App");
HttpPost httpPost = new HttpPost("http://your-server-url");
httpPost.setEntity(new FileEntity(new File("your-file-path"), "application/octet-stream"));
HttpResponse response = httpClient.execute(httpPost);

Java http post: Difference in reading bytes through curl and in java

I am stuck in a strange issue, I am posting some image data to a server, now I created the requested using curl and then traced back it.
Next was to create similar request in java.
The code posts raw binary image data to server, but when I compare the binary data in java to that posted by curl, there is a minute difference due to which I am getting 400 response code from server.
The difference I think is in few dots.
Below is the request generate by curl (linux).
Generate by curl
Now here is the request generate by Java, when I read bytes.
Click here
Java code looks something like this:
PrintWriter out = new PrintWriter(os);
out.println("POST /1izb0rx1 HTTP/1.1");
out.println("User-Agent: curl/7.35.0");
out.println("Host: requestb.in");
out.println("Accept: */*");
out.println("Content-Disposition:inline; filename=test.png");
out.println("Authorization: Basic YW5kcm9pZDpUZXN0dGVzdDExISE=");
out.println("Content-Length: "+"24143");
out.println("Content-Type: application/x-www-form-urlencoded");
out.println();
out.println("."+imgBytes);
Any idea what can be causing this issue ?
Thanks
So,
I got it working, the problem was that certain classes on Android are broken and not behaving as the way they behave on core Java.
The same code that was working on Java, wasn't working here, reason being, a change in header occurring here (On Android).
This issue is very well mentioned here also:
https://github.com/WP-API/WP-API/issues/1862
Thus I was facing a similar issue, and adding external updated jars were conflicting with the ones on Android.
Finally I used a small HTTP Request library: https://github.com/kevinsawicki/http-request
The code is below:
HttpRequest request = HttpRequest.post(url);
request.authorization("Basic "+ah);
request.part("file", fName+".png", "image/png", new File(file));
request.part("title", "test");
if(request.code()==201) {
StringWriter sw = new StringWriter();
request.receive(sw);
onMedia(Media.parse(new JsonParser().parse(sw.toString()).getAsJsonObject()));
}
Thanks
Do not use PrintWriter to send raw bytes.

Jersey servlet returns zip file that contains more bytes than response sent

I'm trying to implement a simple servlet that returns a zip file that is bundled inside the application (simple resource)
So I've implemented the following method in the server side:
#GET
#Path("{path}/{zipfile}")
#Produces("application/zip")
public Response getZipFile(
#PathParam("path") String pathFolder,
#PathParam("zipfile") String zipFile) IOException {
String fullPath= String.format("/WEB-INF/repository/%s/%s",
pathFolder, zipFile);
String realPath = ServletContextHolder.INSTANCE.getServletContext()
.getRealPath(fullPath);
File file = new File(realPath );
ResponseBuilder response = Response.ok((Object) file);
return response.build();
}
When I call this method from the borwser, the zip file is downloaded and its size is the same number of bytes as the original zip in the server.
However, when I call this using a simple XMLHttpRequest from my client side code:
var oXHR = new XMLHttpRequest();
var sUrl = "http://localhost:8080/path/file.zip"
oXHR.open('GET', sUrl);
oXHR.responseType = 'application/zip';
oXHR.send();
I can see in the Network tab of the Developer tools in chrome that the content size is bigger, and I'm unable to process this zip file (for instance JSzip doesn't recognize it).
It seems like somewhere between my response and the final response from org.glassfish.jersey.servlet.ServletContainer, some extra bytes are written/ some encoding is done on the file.
Can you please assist?
Best Regards,
Maxim
When you use an ajax request, the browser expects text (by default) and will try to decode it from UTF-8 (corrupting your data).
Try with oXHR.responseType = "arraybuffer"; : that way, the browser won't change the data and give you the raw content (which will be in oXHR.response).
This solution won't work in IE 6-9 : if you need to support it, check JSZip documentation : http://stuk.github.io/jszip/documentation/howto/read_zip.html
If it's not the right solution, try downloading directly the zip file (without any js code involved) to check if the issue comes from the js side or from the java side.

Categories