Keep form files after validation error

只愿长相守 提交于 2021-01-27 06:53:28

问题


I have a form where I simultaneously send several (let's say 10) files to the backend, along with some other regular input fields.

When I find a validation problem in the backend I display the form again and fill the regular inputs (dropdowns, text inputs, etc.), but I cannot fill the file fields, forcing the user to select the files from the file directory again.

The solution I think of is sending the base64 encoded representation of the files, and put them back in the form in case there is a validation error, but I would like to know if there is a simpler way.


回答1:


No matter what you do, you can not skip server-side validation. For security reasons (someone sending raw requests for example). As far as showing the files in case of error (or simple reloading) I would send it as Base64, but via AJAX if the files are large.

  1. Client-side validation: most validations (if not all) can be done using plain JS. Be it filesize, content type... and more specific validations according to filetypes (image, document...)
  2. Server-side validation: Once sent, fully validate the file and content.
  3. Send files back:In case of error, send the files with the request if small. If big send them via AJAX to avoid blocking and keep page loading times fast.

Hope it helps!




回答2:


The simplest thing to do would be :

1) Validate all fields on the client side (javascript/jquery)

2) Once all other inputs are validated, then you send in Files.

NB: If you need to validate some values on the server side, use ajax for both steps (1) and (2). Also, try to give a bit more details to get quality answers




回答3:


I would create a temporary store for uploaded files and would send back only a unique-hard-to-guess ID got from the store instead than the whole file.

The form section for a single file upload would then include also an hidden input carrying the unique file-ID.

When processing the request: if there is a file in the request get the file (and store it if form not valid) otherwise if there is a file-ID get the file from store.



来源:https://stackoverflow.com/questions/41182809/keep-form-files-after-validation-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!