Tech Tip: Saving User Uploaded Image from Web to Database
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: December 3, 2019
Suppose that you are building a web application with 4D, and you want to have the user upload a profile picture in a form. How do you grab the image file that is uploaded from the form and attach it to the user in the database? Below is a simple strategy to do that.
First, make sure that enctype="multitype/form-data" in the form html tag. This allows files to be sent through the form. Second, the input html tag for the picture should have type="file" and name="photo".
Next, after the user has submitted the file, iterate the "web body parts" until you detect a part named "photo", then convert that part to a picture. This can be done with a simple For Loop and a few 4D commands:
For ($i;1;WEB Get body part count) //for each body part WEB GET BODY PART($i;$contentBlob;$partName;$mimeType;$fileName) If ($partName="photo") & (BLOB size($contentBlob)>0) BLOB TO PICTURE($contentBlob;$img;$mimeType) End if End for |
Now, you can attach the photo to the user. Suppose that the user entity is $user and the attribute for the profile picture is named "picture". Then, you can assign the user's picture attribute to the image created with BLOB TO PICTURE and save to the database:
$user.picture:=$img $user.save() |