Skip to content
Snippets Groups Projects
Commit 2d60ee09 authored by COLLET Ismael's avatar COLLET Ismael
Browse files

push the project

parent 5944f63f
No related branches found
No related tags found
No related merge requests found
File added
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client{
private static CloseableHttpClient client = HttpClients.createDefault();
public static void main(String args[]) throws URISyntaxException, IOException {
String image_path = "image.png";
String ip_address_path = "ip_address";
String endpoint = "/analyseimage";
String ip_address = readTextFile(ip_address_path);
String url_string = "http://"+ip_address+endpoint;
URI uri= new URI(url_string);
File image_file=new File(image_path);
String response = uploadImage(image_file, uri);
System.out.println("Response :\n\n"+response);
}
// This code is inspired by https://gist.github.com/kjlubick/70aea8d38831777360c0, consulted on Dec 13 2020.
private static String uploadImage(File file, URI uri) throws IOException {
// This response handler is from https://www.javaguides.net/2019/07/java-http-getpost-request-example.html
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
System.out.println("Connection to server : "+uri);
HttpPost httpPost = new HttpPost(uri);
String response="";
try {
MultipartEntityBuilder mpeBuilder = MultipartEntityBuilder.create();
mpeBuilder.addBinaryBody("image", file);
HttpEntity content = mpeBuilder.build();
httpPost.setEntity(content);
response = client.execute(httpPost, responseHandler);
} catch(Exception e ){
System.out.println("Error : the file could not be upload.");
} finally {
httpPost.reset();
return response;
}
}
// From https://www.w3schools.com/java/java_files_read.asp
private static String readTextFile(String path){
try {
File file = new File(path);
Scanner myReader = new Scanner(file);
String data="";
while (myReader.hasNextLine()) {
data += myReader.nextLine();
}
myReader.close();
return data;
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
return null;
}
}
}
\ No newline at end of file
# Client side folder
## How to run the program
To run the client program (source code : [Client.java](./Client.java)) :
1. Run [install_jre.sh](install_jre.sh) if it is not installed yet.
2. Write the server's ip address in [ip_address](ip_address).
3. Run [run.sh](run.sh).
## Kotlin code
I tried to do the program with kotlin ([client.kt](client.kt) and [client.jar](client.jar)). But I kept getting an error, so I switched to java.
File added
/*
How to compile & launch this program :
kotlinc client.kt -include-runtime -jvm-target 1.8 -d client.jar
java -jar client.jar
*/
import java.io.File
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse.BodyHandlers
import java.net.URI
import java.nio.file.Path
fun main() {
val image_path = "image.png";
val url_path = "url";
// Read the url
val url = File(url_path).readText(Charsets.UTF_8);
println("Image will be sent to : " + url);
// Build the client
val client = HttpClient.newBuilder().build();
// Build the request
val request = HttpRequest.newBuilder()
.header("Content-Type", "image")
.POST(HttpRequest.BodyPublishers.ofFile(Path.of(image_path)))
.uri(URI.create(url))
.build();
// Get the response and print it
val response = client.send(request, BodyHandlers.ofString());
println(response.body())
}
/*
Basically a copy/paste from https://handyopinion.com/upload-file-to-server-in-android-kotlin/
implementation("com.squareup.okhttp3:okhttp:4.9.0")
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
fun main() {
val image_path = "image.png";
val url_path = "url";
// Read the url
val serverURL = File(url_path).readText(Charsets.UTF_8);
val mimeType = getMimeType(sourceFile);
if (mimeType == null) {
println("file error : Not able to get mime type")
return
}
val fileName: String = image_path
toggleProgressDialog(true)
try {
val requestBody: RequestBody =
MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("image", fileName,sourceFile.asRequestBody(mimeType.toMediaTypeOrNull()))
.build()
val request: Request = Request.Builder().url(serverURL).post(requestBody).build()
val response: Response = client.newCall(request).execute()
if (response.isSuccessful) {
println("File uploaded successfully at $serverUploadDirectoryPath$fileName")
} else {
println("File uploading failed")
}
} catch (ex: Exception) {
println("File uploading failed")
}
}
*/
client_side/image.png

562 B

apt update
apt install openjdk-7-jre
\ No newline at end of file
172.17.0.2
\ No newline at end of file
java -jar client.jar
\ No newline at end of file
# Server side folder
## How to run the API
To run the API (source code : [api.py](./api.py)) :
1. Run [install_python_and_flask.sh](install_python_and_flask.sh) if it is not installed yet.
2. Run [run.sh](run.sh).
import flask, os
from flask import request, jsonify
from image_analyser import analyse as analyse_image
app = flask.Flask(__name__)
app.config["DEBUG"] = True
app.config['upload_folder']="./images"
@app.route('/', methods=['GET', 'POST'])
def home():
return '''
<h1>This site is for research purpose</h1>
<p>To send an image and receive an answer, use the '/analyseimage' endpoint.</p>'''
'''How to use this endpoint with curl (=on a linux terminal):
curl -X POST -F 'image=@[path to the image]' http://[ip address]/analyseimage
'''
@app.route('/analyseimage', methods=['POST'])
def api_analyseimage():
#Store the image as 'images/[hash_of_the_image].[extension]
try :
file = request.files['image']
except :
if len(request.files)==1 :
file = request.files[
list(request.files.keys())[0] # File = the only element in request.files
]
else :
return "Error : Image not found."
try :
extension = os.path.splitext(file.filename)[-1]
filename=str(hash(file))+extension
filepath = os.path.join(app.config['upload_folder'], filename)
file.save(filepath)
# Analyse the image
result=analyse_image(filepath)
# Remove the image and send back the result
os.remove(filepath)
return jsonify(result)
except :
return("Error while analyzing the image.")
@app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
app.run(host = '0.0.0.0', port=80)
\ No newline at end of file
from PIL import Image
#Return the first and last pixels
def analyse(path):
try :
im = Image.open(path).getdata() #Load the image as a list of tuples
im = list(im)
return {
"First pixel" : str(im[0]),
"Last pixel" : str(im[len(im)-1])
}
except :
return "Error in the analyse of image"
\ No newline at end of file
This folder is used to store images.
apt update
apt install python3-pip
pip3 install flask
\ No newline at end of file
python3 api.py
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment