Problems submitting an image using MultipartRequest

20 views
Skip to first unread message

rdvg...@gmail.com

unread,
Jun 29, 2021, 7:37:59 PM6/29/21
to CodenameOne Discussions
Hi,

I am working on a WS made in PHP. I was able to create some routines to receive an image and save them in a folder on the server. All this I have been testing in Postman and it works 100%.
In the WS I do not validate the HTTP method, but I assume it is POST.

From my mobile app I send the file with the MultipartRequest class. I was able to validate by debugging the response code 200, however I can't get the file to be created in the folder.

I have 3 days struggling with this and I don't see the problem. I copy the code to see if you can see the error.

I take this opportunity to ask if it is valid to send additional arguments, since I need to send the name of the database and the company code to create the folder where the image will be saved.

My code:
    public static void actualizaImagenFoto(String rutaImagen, Long visitaId) {
        try {
            MultipartRequest mp = new MultipartRequest();
            mp.setUrl(SERVER_URL + "ws_foto_imagen/ws_foto_imagen.php");
 //           mp.addArgument("token", UsuarioService.getToken());
 //           mp.addArgument("fot_visita_id", visitaId.toString());
            mp.addData("imagen", rutaImagen, "image/jpeg");
            addToQueue(mp);
            System.out.println(Integer.toString(mp.getResponseCode()) + "   " + mp.getResponseErrorMessage());
        } catch (IOException err) {
            Log.e(err);
            ToastBar.showErrorMessage("Error en actualización de la foto: " + err.getMessage());
        }
    }

rdvg...@gmail.com

unread,
Jun 29, 2021, 8:15:35 PM6/29/21
to CodenameOne Discussions
Hi,

Detect the problem by including the following parameters:
             mp.setFilename ("image", "data.jpeg");
             mp.setPost (true);

However, I would like to know how I can send 2 additional arguments (Database and Company Number).

Thanks

Shai Almog

unread,
Jun 29, 2021, 9:33:36 PM6/29/21
to CodenameOne Discussions
Hi,
using the regular addArgument should work just fine. It will be added to the multipart seamlessly.

rdvg...@gmail.com

unread,
Jun 29, 2021, 10:22:23 PM6/29/21
to CodenameOne Discussions
Hi,

I asked him about the arguments because I did not get the ws to recognize them

Javier Anton

unread,
Jun 30, 2021, 1:04:09 AM6/30/21
to codenameone...@googlegroups.com
Can't be sure without looking at your entire implementation but here are 2 ideas:

1- make sure to add the file via MultipartRequest.addData( and don't call setPost or setFileName


--
You received this message because you are subscribed to the Google Groups "CodenameOne Discussions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to codenameone-discu...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/codenameone-discussions/2320c9e6-4b91-412c-b04f-55ba6587c88cn%40googlegroups.com.

rdvg...@gmail.com

unread,
Jun 30, 2021, 12:26:32 PM6/30/21
to CodenameOne Discussions
Hi,

Thank you mr Shai and mr Javier for your reply
I thought it worked, but I was wrong.
I'm going to name everything I've done. As I mentioned in postman it works fine and this is the configuration:
Postman.png
The code in PHP is small and although it is not the topic of this forum I am going to include it (suddenly someone detects a problem):
//Coloca los encabezados 
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE');  
header('Content-Type: application/json; text/html; charset=UTF-8; multipart/form-data');
header('Access-Control-Max-Age: 3600');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
// Generar archivo .htaccess si es necesario.
ws_htaccess();

$bd = isset($_GET['bd']) ? $_GET['bd'] : null;
if (isset($_FILES['imagen']['name'])) {
$fileName  =  $_FILES['imagen']['name'];
$tempPath  =  $_FILES['imagen']['tmp_name'];
// Extensiones validas
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); 
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // toma la extension de la imagen
if (in_array($ext, $valid_extensions)) { // Valida que la extensión sea valida
$ruta = "../../../file/img/".$bd."/imagen";
if (!file_exists($ruta)) {
mkdir($ruta, 0777, true);
}
move_uploaded_file($tempPath, $ruta."/".$fileName);
}
} else {
return getResponse('error', null, 500, 'Fallo en la creación / actualización de la foto');
}


And finally the code in the mobile app:
public static void actualizaImagenFoto(String imagen, String rutaImagen) {
        try {
            MultipartRequest mp = new MultipartRequest();
            mp.setUrl(SERVER_URL + "ws_foto_imagen/ws_foto_imagen.php");
            mp.addArgument("bd", Preferences.get("bd", "tempus"));
            mp.addData("imagen", rutaImagen, "image/jpeg");
            mp.setFilename("imagen", imagen);
            mp.setPost(true);
            System.out.println(Integer.toString(mp.getResponseCode()) + "   " + mp.getResponseErrorMessage());
        } catch (IOException err) {
            Log.e(err);
            ToastBar.showErrorMessage("Error en actualización de la foto: " + err.getMessage());
        }
    }

With or without the setPost and setFileName methods it's not working for me.

I appreciate your comments because I do not know what to continue doing.

rdvg...@gmail.com

unread,
Jun 30, 2021, 2:59:33 PM6/30/21
to CodenameOne Discussions
Hi,

Uff, at some point delete the line "addToQueue (mp);". Also note that although in Postman I use the "POST" method it is necessary for the parameters to be detected in PHP with $ _GET ['variable'], however when it is executed from a client it is necessary to use $ _POST ['variable'].

Thanks for the support and sorry for the inconvenience.

Shai Almog

unread,
Jun 30, 2021, 10:02:22 PM6/30/21
to CodenameOne Discussions
Hi,
multipart is a multipart file upload. Which isn't "form-data" it's "x-www-form-urlencode" which is a very different thing.
If you don't need that you shouldn't use multipart and should use a regular connection request. Just submit the file as a byte[].

If an argument is passed as get just pass it manually in the URL by adding it to the string using the ? and & characters.
Reply all
Reply to author
Forward
0 new messages