0

I want to upload a variable number (user defined) number of files through retro fit to php (photos in this case) to use in my php code. I believe I have the retrofit code but I'm not sure how to do the php/slim code and I can't seem to find an answer. I have searched.

So my android java is something like this in thinking. To upload the variable number of files from the phone to the server.

caption[] = (cap1, cap2, cap3);
Uri[] = (user selected Uri, second uri, third uri, .....as selected);
x = Uri[].length;

private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
    File file = FileUtils.getFile(this, fileUri);
    RequestBody requestFile =
        RequestBody.create(
            MediaType.parse(getContentResolver().getType(fileUri)),
            file
        );
    return MultipartBody.Part.createFormData(partName, file.getName(),
        requestFile);
}

List < MultipartBody.Part > parts = new ArrayList < > ();
While(x >= 0) {
        photo = "photo" + x;
        parts.add(prepareFilePart(photo, Uri[x]));
        x = x - 1;
    }
    ...
Call < ResponseBody > call = service.uploadMultipleFilesDynamic(description, parts);

with a call of

Call<ResponseBody> uploadMultipleFilesDynamic(
        @Field("cap[]") ArrayList<String> capation[],
        @Part List<MultipartBody.Part> files);
     }

Now the php is where I have some real questions as I don't know how to receive this.

Currently for 1 file I do something like this in slim.

$response = array();

if (isset($_POST['cap']) &&
    ($_POST['IDs']) &&
    ($_POST['filenamev']) &&
    $_FILES['image']['error'] === UPLOAD_ERR_OK) {

    $upload = new pictureuploads();

    $filep = $_FILES['image']['tmp_name'];
    $capp = $_POST['cap'];
    $ID = $_POST['IDs'];
    $desc = $_POST['filenamev'];

    if ($upload->savecapFile($filep, getFileExtension($_FILES['image']['name']), $desc, $ID, $capp)) {
        $response['error'] = false;
        $response['message'] = 'File Uploaded Successfullly';
    } else {
        $response['error'] = true;
        $response['message'] = 'Required parameters are not available';
    }
    echo json_encode($response);
}

with the method being used as.

public function savecapFile($filep, $extension, $desc, $ID, $timep)
{
    move_uploaded_file($filep, $filedest);
}

So my question is, how do I accept the variable number of files in the php?

The results I would like are simple.

A random number of user defined files gets uploaded. Right now I have to have a 1 for 1 link in my receiving files. I would like to not have to worry about that so the user can upload as many as they choose.

Neha
  • 2,136
  • 5
  • 21
  • 50
Robert
  • 1
  • 5
  • I don't think this a Slim Framework related question. – odan Jun 23 '19 at 18:46
  • Uploading multiple files. This question has be answered already here: https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php – odan Jun 23 '19 at 18:55
  • thank you, i could not find that. but one question, can I pass that array to the middle ware where my function actually takes place. How does that look? Do I pass it the same way? Something like getFileExtension($_FILES['image'] or is there another way? – Robert Jun 23 '19 at 19:59
  • In Slim you can (and should) use the `$response` object to get all request specific values. Better don't use `$_POST` anymore. This here works within a middleware too: `$uploadedFiles = $request->getUploadedFiles();` [More details](http://www.slimframework.com/docs/v3/cookbook/uploading-files.html) – odan Jun 23 '19 at 20:24
  • yeah see I didn't really understand that page because I was never taught the $request->getUploadedFiles(); I only learned on youtube But just to make this clear. if I did do something like, $uploadedFiles = $request->getUploadedFiles(); I could then pass $uploadedFiles to the middleware like $upload->savecapFile($uploadedFIles, $desc, $ID, $capp and then in the middleware do foreach ($uploadedFiles['example2'] as $uploadedFile) { if ($uploadedFile->getError() === UPLOAD_ERR_OK) { $filename = moveUploadedFile($directory, $uploadedFile); that should work? – Robert Jun 23 '19 at 20:48
  • I think for this kind of functionality, a middleware isn't the right approach. Better implement this logic within a "controller action" or [route callback](http://www.slimframework.com/docs/v3/objects/router.html#how-to-create-routes) if you want. – odan Jun 23 '19 at 22:00
  • you can put a route inside of a route? It is already in a route $app->post('/caption', function(Request $request, Response $response){ The response array then leads to the code in php above. where I try to send it to the method I need here $upload->savecapFile...... otherwise I think you just talked over my head and I don't understand. – Robert Jun 23 '19 at 22:56
  • You said "[middleware](http://www.slimframework.com/docs/v3/concepts/middleware.html)" and this is something different then a route (action) in Slim. – odan Jun 24 '19 at 08:06
  • ok I'm sorry yeah php isn't my strong suit which probably is why I'm here. I guess what I do is a route and then a call? I'm trying to figure out how to take my string arrays and then my multipart files into the call. Can i just send $request_data = $request->getParsedBody(); the request data into the call like so something like . $upload = new videouploads(); if.... $upload->saveFile($request_data);...return a response. if not how accept it and to send the array over in the call. from within the route.aka $app->post('/savefile', function(Request $request, Response $response) – Robert Jun 27 '19 at 01:05
  • I just added an answer with example code. I hope it helps. – odan Jun 27 '19 at 07:29

1 Answers1

0

Try this generic example:

$app->post('/savefile', function (Request $request, Response $response) {
    $post = $request->getParsedBody();
    $files = $request->getUploadedFiles();

    // Custom validation
    if (!isset($post['cap'], $post['IDs'], $post['filenamev'])) {
        // Send validation error code 422
        return $response->withJson([
            'message' => 'Required parameters are not available',
        ])->withStatus(422);
    }

    // Validation passed

    // Save files to this directory
    $destination = 'storage/';

    try {
        $uploadedKeys = array_keys($files['image']['tmp_name']);

        foreach ($uploadedKeys as $key) {
            $tempFile = $files['image']['tmp_name'][$key];
            $filename = $files['image']['name'][$key];
            //$extension = pathinfo($filename , PATHINFO_EXTENSION);
            if (!move_uploaded_file($tempFile, $destination)) {
                throw new RuntimeException(sprintf('Upload failed: %s', $filename));
            }
        }

        // Send OK
        return $response->withJson([
            'success' => true,
            'message' => 'Files uploaded successfully',
        ])->withStatus(200);
    } catch (Exception $exception) {
        // Send error message
        return $response->withJson([
            'message' => sprintf('Upload failed with error: %s', $exception->getMessage()),
        ])->withStatus(500);
    }
});
odan
  • 4,757
  • 5
  • 20
  • 49