Jump to content
MatthewSchenker

Create Pages (with File-Upload Field) via API

Recommended Posts

@videokid: ok that with readability is personal. agread

but could you explain why that did the trick for me?

 
but what trick does it?
 

if($upload_path.$filename !== $upload_path . $filename) echo 'Horst is wrong!';
else echo 'This is nonsense!';
  • Like 2

Share this post


Link to post
Share on other sites

The dot concatenates the right and left variables (strings), no matter when you use spaces or not. 

oftopic:

// 'concatenating numbers'
echo  6 . 6; //echo's the string 66
echo 6.6;    //echo's the float 6.6
  • Like 1

Share this post


Link to post
Share on other sites

I was always under the impression it didn't matter...

I've done some testing and in the end it seems

'This is nonsense! Horst is right'

however, putting back the spaces results in a not deleted file in the temp directory.... without the spaces... woosh temp file gone...  ???

Debug time!

Share this post


Link to post
Share on other sites

Hello Matthew

I saw in your code  under  "HANDLING MULTIPLE FILE-UPLOAD FIELDS IN THE SAME FORM".. I have done this by adding multiple in HTML form. This way there was no need to keep extra fields and run extra executes (Run foreach). Every thing was working fine until I put the file field inside a repeater. Now the new file is replacing older one inside repeater.

I am searching for solution but No luck. Any help is much appreciated.

here is my code:

$p2= pages->get($id);
$pdfs = new WireUpload('f_plan');
    $pdfs->setMaxFiles(8);
    $pdfs->setOverwrite(false);
    $pdfs->setDestinationPath($upload_path);
    $pdfs->setValidExtensions(array('pdf','xps'));

// execute upload and check for errors
    $pdf_files = $pdfs->execute();
    echo count($pdf_files); //count is showing number of files
    if(!count($pdf_files))
    {
    $pdfs->error("Sorry, but you need to add a file!");
    return false;
    }
    
    foreach($pdf_files as $filename)
    {
    $p2->of(false);
    $new_rep = $p2->floor_plan_rep->getNew(); //floor_plan_rep is my repeater with one file field inside named floor_plan.
    $p2->save();
    echo $pathname = $upload_path . $filename; //all the urls are okey
    $new_rep->floor_plan = $pathname;
    $p2->save();
    $p2->of(true);
    unlink($pathname);
    }

Share this post


Link to post
Share on other sites

After a few days of research I found this solution for my above problem.

Complete code is--

<?php

if ( isset($_POST['submit']) ) {

 $upload_path = $config->paths->templates . "images/";
$pdfs = new WireUpload('upload');
    $pdfs->setMaxFiles(8);
    $pdfs->setOverwrite(false);
    $pdfs->setDestinationPath($upload_path);
    $pdfs->setValidExtensions(array('pdf','xps','pptx'));

// execute upload and check for errors
   $pdf_files = $pdfs->execute();

    if(!count($pdf_files))
    {
    $pdfs->error("Sorry, but you need to add a photo!");
    return false;
    }
    $rep_id = array();
         $page->setOutputFormatting(false);
    foreach($pdf_files as $pdf){

        $building = $page->test_rep->getNew();
        $building->save();
        $rep_id[] = $building->id;
        $page->test_rep->add($building);

    }
            $page->save();
            $page->setOutputFormatting(true);



     if(count($rep_id) === count($pdf_files)){
        $count = 0;

        foreach($pdf_files as $pdf){
            $page->setOutputFormatting(false);
            $repeater_id = $rep_id[$count];
            $field_rep = $page->test_rep->get("id=$repeater_id"); // test_rep is table and test_rep_field is field of the table
            $field_rep->of(false);
            $field_rep->test_rep_field = $upload_path.$pdf;
            $field_rep->save();
            $page->save("test_rep");
            $page->setOutputFormatting(true);
            $count++;
        }

     }


  }
?>

<form action="<?php $_SERVER['PHP_SELF'] ;?>" method="post" enctype="multipart/form-data">

<p>Click the "Select Files" button below to upload your photo.</p>
<input type="file" name="upload[]" multiple />
<button type="submit" name="submit">Submit</button>
</form>

I hope this will help someone while uploading files in repeater fields.

  • Like 2

Share this post


Link to post
Share on other sites

How can i check if the user has choosen a valid file?

For example: User choose pdf but allowed is only jpg.

Check or prevent? If prevent:

$u = new WireUpload('files');
$u->setValidExtensions(array('pdf','xps','pptx'));
// etc..

Share this post


Link to post
Share on other sites

I used the code from here and modified it. And i have this:

// New wire upload
$service_upload = new WireUpload('service_file_upload_sw'); // References the name of the field in the HTML form that uploads the photo
$service_upload->setMaxFiles(5);
$service_upload->setOverwrite(false);
$service_upload->setDestinationPath($upload_path);
$service_upload->setValidExtensions(array('jpg', 'jpeg', 'png', 'tif', 'tiff', 'gif'));

When i now choose a pdf file and hit the submit button then there is no wrong file message.

Share this post


Link to post
Share on other sites

Hello Marcel,

in my case I had two level of validation,first via html form pattern,Second the above one. try to get error message with 

$service_upload->error();

Also if it dosent help get file names and extension with core php

$file_ext = $_FILES['my-file']['type'] ;

and check for right file.

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By VeiJari
      Hello forum,
      This is really a weird one, because front end editing works in a earlier website we did to a customer. 
      When I check the source code for current website it does initiate front end edit: 
      <span id=pw-edit-1 class='pw-edit pw-edit-InputfieldPageTitle' data-name=title data-page=1021 data-lang='1017' style='position:relative'><span class=pw-edit-orig>Tekijät</span><span class=pw-edit-copy id=pw-editor-title-1021 style='display:none;-webkit-user-select:text;user- select:text;' contenteditable>Tekijät</span></span>  But when I double click nothing happens (yes I'm 100% sure I'm superuser and logged in)
      I also tried to apply the front end with other methods than:
      $page->edit('title'); But didn't work either.
      We are using jquery 2.2.4, so it should not be a problem.
      Is this a bug related to current master or something else?
      Someone else having this problem as well?
    • By jom
      Hi everyone
      It seems that I don't fully understand the wireTempPath() function and I need some help.
      I use wireTempPath() to create a new location in assets/cache/WireTempDir and than copy a pdf from the assets/files/page folder to the new folder. I want the file to be accessible only for a limited time, that's why I use wireTempPath.
      The file seems to be copied to the right location, but gets deleted right afterwards, according to 
      As mentioned in the topic above, 
      $wireTempDir->setRemove(false); prevents the file to be deleted. But I like the file to be automatically deleted after a few days. So, how can I do that?
      My code so far (everything works, but the automatic removal of the tempDir folder):
      //generate and show download link $folder = time(); // timestamp as temporary folder $maxAge = (int) $settings->options_downloadlink_valid_hours * 3600; //tempDir wants maxAge as seconds $options = array( 'maxAge' => $maxAge ); $wireTempDir = wireTempDir($folder, $options); $wireTempDir->setRemove(false); $src_file = $page->ebook_download->filename; // Create a new directory in ProcessWire's cache dir if(wire('files')->mkdir($wireTempDir, $recursive = true)) { if(wire('files')->copy($src_file, $wireTempDir)){ //get subdirs from tempDir: $pos = strpos($wireTempDir, "WireTempDir"); $subdir = substr($wireTempDir, $pos, 100); $out .= "<p><a href='" . wire('pages')->get('template=passthrough')->httpUrl . "?file=" . $subdir . $page->ebook_download->basename . "' target='_blank'>$page->title</a></p>"; } } I appreciate any ideas - thanks!
      Oliver
    • By VeiJari
      Hello forum, this is my first security related post, so I'm a bit of a newbie.
      I understand that when I have direct front-input from user I should sanitize the input, but how about when I use a secret key for showing a API for a third-party supplier? Should I sanitize the input->get() key?
      I've tested this issue and I tried ?key=<?php echo $page->field; ?> And without adding any sanitization it comes back: /?key=<?php%20echo%20$page->field;%20?>
      So can I rely on this, or should I still use $sanitizer just in case?
       
      Thanks for the help!
    • By EyeDentify
      I have been experimenting with the new $page->meta() method and find it useful.

      Once i figured out that the data i "save" with it is tied to the page where i called the method from.

      So this is not obvious at least not for me in the documentation:
      https://processwire.com/api/ref/page/meta/
       
      So i just wanted to share that revelation with the community so you don´t get as confused as i was.

      Happy Coding Everyone.
    • By louisstephens
      Going through my long quest to get better with ajax and utilizing the api, I have hit yet another roadblock. I currently have a form with an image field (thanks to flydev for getting that sorted), "title" text input, and a select field set to multiple. In my ajax call, I added in:
      tags = $("#select-tags").val(); form_data.append('tags', tags); $.ajax({ type: 'POST', data: form_data, contentType: false, processData: false, url: '/ajax/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); And in the ajax template: 
      $tags = $sanitizer->text($_POST['tags']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->tags = $tags; $p->save(); If I select a "tag" from the select input and submit, it does indeed add it to the Page Reference field in the backend. However, this does not work with an array being passed to it of multiple options.

      So it does appear that my ajax call is trying to submit multiple options, but I am really just unsure how to get these two added in. I saw in other forums posts of add($page) and even add(array()). Do I need to handle this js array differently or do  I need to foreach through the $tags to add it like:
      foreach($tags as $tag) { $p->tags->add($tag); $p->save(); } I tried this approach, but apparently I am still missing something.
       
      Edit:
      I was doing some tweaking, and I know I can split the js array out like:
      for (i = 0, len = tags.length; i < len; i++) { console.log(tags[i]); } However, I am not sure then how to handle the POST in php if I were to split it out.
×
×
  • Create New...