Gaurav
Gaurav

Reputation: 367

How can I prepopulate a file input?

I'm working on a job board site which submits user applications to a third party site. The users have to provide following information while applying: name, contact details and resume. Since these fields are also available on user profile on the site, we want to pre populate the form fields, allowing users to change the information as they like.

Now, all other fields can be populated without an issue. However, file input field can't be populated due to security violations. Is there a work around possible using FILE API and BLOB objects?

What I'm planning to do is the following:

  1. Create a blob object from file URL on server
  2. Read the blob as an array buffer using FileReader.
  3. Attach this file to file input field <- this is what I'm not able to figure out and need help with.

Also, if there is any alternate way to achieve this, please let me know. I'm using PHP and JavaScript to generate the form, so I can do the preprocessing in PHP.

Upvotes: 4

Views: 5531

Answers (2)

Gaurav
Gaurav

Reputation: 367

Creating an answer just to give a little more insights into how I solved this issue, and why there was an issue in the first place.

Background: I've created a custom WordPress plugin for a client, which fetches the job applications from various sites, and displays them inline. We also allowed application submission, where the users could attach their resume, and the same was submitted to the original job posting. Since, a lot of users access the website on their mobile, they do not have the resume available on the same. In such a case, we wanted to offer them a facility to use a resume stored on their profile.

Potential Solution: The simplest way to do this would've been to fetch the file contents via ajax from user's profile, and attach it to the form before submission. However, for whatever reason, this didn't work.

Applied Solution: The solution that worked is pretty old school. Instead of submitting the application directly, we submitted it to an intermediate page, which fetched the file contents from user's profile, modified the form data and submitted via curl. This also saved the double data exchange on user's end (file download and re-upload).

Upvotes: 0

guest271314
guest271314

Reputation: 1

  1. Attach this file to file input field <- this is what I'm not able to figure out and need help with.

It is not possible to set a value at FileList object of <input type="file"> element.

You can create and append a File object to a FormData object and submit FormData using XMLHttpRequest()

var data = new FormData();
data.append("file", /* Blob | File */, "filename.ext")

Upvotes: 3

Related Questions