artyom-beilis / cppcms

CppCMS Framework
Other
443 stars 107 forks source link

Making a file upload optional in a form #80

Open jkalyanapu opened 3 years ago

jkalyanapu commented 3 years ago

I currently have a form in my application, but if I don't upload a file in the form the form will fail to validate. Here are the relevant parts of my content.h

struct submit_op_form : public cppcms::form {
    cppcms::widgets::file image;
    submit_op_form() {
      image.limits(0,500*1024);
      image.mime(booster::regex("(image/(png|jpeg))|$")); //Allow mimetypes of either image/png or image/jpeg

      image.filename(booster::regex("([_a-zA-Z0-9]+\\.(png|jpg|jpeg))")); //Allow filenames of the form [text consisting of alphanumeric characters].png/jpg/jpeg
      image.mime(booster::regex("(image/(png|jpeg))")); //Allow mimetypes of either image/png or image/jpeg
      image.add_valid_magic("\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"); //magic numbers for png files
      image.add_valid_magic("\xff\xd8"); //magic numbers for jpeg files
      image.add_valid_magic("");
      add(image);
    }
    virtual bool validate() {
      if (!form::validate()) {
    return false;
      }
      return true;
    }
  };

More specifically, I never called image.non_empty() and I added an empty string as a valid magic number but the form still fails to validate.

artyom-beilis commented 3 years ago

Thanks for reporting.

It is indeed a bug and I'm quite surprised that it wasn't discovered till now!! I'll write a fix asap.

artyom-beilis commented 3 years ago

I'm trying to understand how to solve the issue in correct way since what I see "file" is provided but its name empty and it size 0 and its content-type is `application/octet-stream'

So if you add these conditions it will work as "workaround" till I fix the issue properly.