Upload image from android app gallery to local spring server - java

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);

Related

How to get URL of mp3 when it is playing

We can play mp3 files from browsers, Social Networks, Apps... I want to get URL of mp3 when it's playing. One way here is to create an extension in the browser. But in other apps we can't. Here is an example:
I go to some site and open some mp3:
If you can see the music is playing and it has a URL. I want to get this URL when music starts playing. How can I do that? And how can I get URL of music which is playing in some app? Is it possible?
If you can see the music is playing and it has a URL. I want to get
this URL when music starts playing. How can I do that?
If you are loading the website into a WebView, the easiest possible way you can get the URL by intercept the requests through WebViewClient and check if the URL contains '.mp3'. See the following example,
public class YourWebViewClient extends WebViewClient {
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(".mp3")) {
Log.d(TAG, "MP3 url = [" + url + "]");
}
return super.shouldInterceptRequest(view, request);
}
}
And how can I get URL of music which is playing in some app? Is it
possible?
Yes possible but not too easy especially if you are going to get it from SSL traffic. To sniff other app's network traffic you need to perform MITM. There are a couple of apps in the play store which are doing exactly the same thing. You can look into HttpCanary app for reference. Basically you need to perform the following steps -
Set up a proxy server
Configure your device to pass its network traffic to that proxy server
Ask the proxy server to give you the network data
Analyze the network data to see if it contains 'mp3' URL
If you need to intercept https traffic, you need to generate and install an SSL certificate.
First import the JSOUP library from maven
compile 'org.jsoup:jsoup:1.12.1'
after that use this code
Document doc = Jsoup.connect(url).get();
System.out.println(doc.title());
Elements h1s = doc.select(".jp-type-single");
System.out.println("Number of results: " + h1s.size());
for (Element element : h1s) {
String mp3Url = element.attr("data-xc-filepath");
System.out.println("mp3 url: " + mp3Url);
file_num++;
URLConnection conn = new URL(mp3Url).openConnection();
InputStream is = conn.getInputStream();
OutputStream outstream = new FileOutputStream(new
File("/users/pelican/downloads/"+file_num+"file.mp3"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
now let me explain this
JSOUP fetched the webpage using your HTML URL
after that, it converts into doc
and after that, it selects the element by using a select method and here we are getting the first audio tag that we want to search.

Resumable upload to GCS from Android client using `upload_id` for auth

This is from the GCS Access Control documentation on signed URLs and it matches my use case exactly (the resumable upload scenario):
Note: If your users are only uploading resources (writing) to an
access-controlled bucket, you can use the resumable uploads
functionality of Google Cloud Storage, and avoid signing URLs or
requiring a Google account. In a resumable upload scenario, your
(server-side) code authenticates and initiates an upload to Google
Cloud Storage without actually uploading any data. The initiation
request returns an upload ID, which can then be used in a client
request to upload the data. The client request does not need to be
signed because the upload ID, in effect, acts as an authentication
token. If you choose this path, be sure to transmit the upload ID over
HTTPS.
I have a GAE instance which successfully authenticates and initiates a resumable upload to GCS. As expected, GCS returns my GAE server a response:
HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/storage/v1/b/<my-apps-default-bucket>/o?uploadType=resumable&name=<my-file-name>&upload_id=xa298sd_sdlkj2
Content-Length: 0
The GAE server hands the Android client the URL from the above location and the Android client uses this to try to PUT the file to GCS. Here is the basic code snippet used:
HttpClient client = new DefaultHttpClient();
String url = <URL-returned in Location-Header>; // exactly the URL returned in the GCS response above
Log.v("PUT URL", url);
HttpPut put = new HttpPut(url);
put.addHeader("Content-Type", "<my-file-mime-type>");
// Note that HttpPut adds the `Content_Length` based on the entity added. Doing it by hand will throw an Exception
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("file", new File("<path-to-my-file>"));
HttpEntity entity = entityBuilder.build();
put.setEntity(entity);
HttpResponse response = client.execute(put);
HttpEntity httpEntity = response.getEntity();
responseMsg = EntityUtils.toString(httpEntity);
Log.v("resultMsg", responseMsg);
Logs show the response from GCS for the above PUT is:
{
"error":{
"errors":[
{
"domain":"global",
"reason":"badRequest",
"message":"Invalid Upload Request"
}
],
"code":400,
"message":"Invalid Upload Request"
}
}
My question is to anyone who has gotten the resumable upload scenario to work for this use case: (1) Client asks server to initiate resumable upload, (2) server initiates upload and gets Location with upload_id, (3) server passes these to client, (4) client uses these to upload file to GCS directly with no additional authentication (no signed URL). Is there something I'm missing? According to the documentation it looks like this approach should be working. Does anyone have pointers or experience that could help me out?
Thanks.

Android SDK : Samba server streaming video to Android using VideoView?

I need play video from samba to android device streaming. I've been look for this question and someone say that :
Using JCIFS to scan for and "see" the share: http://jcifs.samba.org/
Implementing a simple HTTP server (NanoHttpd) to stream the content
via http: https://github.com/NanoHttpd/nanohttpd
Passing the http://localhost/myvideo link to the VideoView
I'm already use JCIFS to get SmbFile in my project and I also get inputstream( smbfile.getInputStream() ).
Now I import NanoHttpd and I create simple HTTP server that http address ishttp://localhost:8080
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(8080);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
InputStream is = new SmbFile(filePath,auth).getInputStream();
//return index as response
return new NanoHTTPD.Response(HTTP_OK, "video/mp4", is);
}
}
server = new MyHTTPD();
server.start();
But my http address is different from http://localhost/myvideo, I don't know how to get right http address and put it in to VideoView.
I don't know how to get path like http://localhost/myvideo .
Thanks for help....
The other question : Can I use VideoView playing video from InputStream ?

uploading png to server with java using POST data

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.

IOException when Uploading Videos to YouTube via Java API

I have been attempting to upload videos to YouTube via the JavaAPI using Direct Uploading. I have been having a problem when I call the insert() method, I get a IOException with the error message
"Error writing request body to the server"
I have verified that the File object I am creating is correct as well as all the details in my VideoEntry object. I have been using Fiddler to monitor the activity from my machine and no request is made to the upload API so the problem is not there. Here is a summary of the code I am using:
VideoEntry newVideo = new VideoEntry();
//Defined video properties such as title and description here.
MediaFileSource ms = new MediaFileSource(videoFile, "video/flv");
newVideo.setMediaSource(ms);
VideoEntry createdEntry = settings.insert(new URL(apiUrl), newVideo);
The IOException is thrown on the insert call (settings is my YouTubeService instance) and the API URL appears to be correct.
Prior to this I have succeeded in uploading this video using the C# API so I know the video file is valid.
--Update
This is the apiURL value:
http://uploads.gdata.youtube.com/feeds/api/users/default/uploads
Make certain that videoFile actually points to the correct local file. The File(String) constructor won't verify that it actually exists. The MediaFileSource constructor and VideoEntry.setMediaSource() method also never check that the file is valid. The error message "Error writing request body to the server" sounds like the insert method can not find the body of the message it is trying to send.
File videoFile = new File("...");
if (videoFile.exists() == false) {
System.err.println("FAIL");
}
to test if the file exists.
If you are under a firewall env and had configured your proxy settings in jvm system properties. The try configuring your youtube service as:
service.setChunkedMediaUpload(MediaService.NO_CHUNKED_MEDIA_REQUEST);
or in your case
settings.setChunkedMediaUpload(MediaService.NO_CHUNKED_MEDIA_REQUEST);
since as you say is your YouTubeService instance.
hope this helps.

Categories