zkytony
zkytony

Reputation: 1508

Reassign the uploaded file from one "file" type input to another

I have a form for a mini-post, and the design wants there to be an image file uploader inside the form, and display selected image to replace the form uploader once the user has chosen an image file.

Right now, I intend to have another form, "image upload", outside the main form (for the mini-post). When the user selects the file, the image upload form will be submitted, and saves the file to the server via AJAX. Fields inside the image upload form will be hidden.

Certainly, I need to place the image file selector HTML inside the mini-post form's HTML because of positioning. Then, how do I reassign the "file", not just the filename, chosen via the file selector in the main form to a hidden "file" type input inside the image upload form?

I am not sure if this is possible. If it is not possible, what would be a suggestion for implementing this design?

Upvotes: 0

Views: 136

Answers (2)

zkytony
zkytony

Reputation: 1508

Using the method provided by @fauxerious: to send this object with JQuery ajax (for Rails):

$.ajax({
    type: 'post',
    url: //action to handle this ajax,
    data: formdata,  // formdata is obtained from handleForm()
                     // it has a property "file".
    contentType: false,
    processData: false,
    dataType: 'json', // get back json
    success: function(output) {
      alert(output);
    }
});

In the Rails action, just access this file via params[:file], and then use CarrierWave to handle it.

Upvotes: 2

Donnie D'Amato
Donnie D'Amato

Reputation: 3940

You could potentially use FormData.

function handleForm(){
    var formdata = new FormData();
    var file = $('input[type="file"]').prop('files')[0];
    if (file.type == 'image/jpeg') {
        formdata.append('file', file);
        return formdata;
    };
};

This with return an object that you can pass like data from a multipart form into an AJAX request. I've added a conditional here to check for jpeg but you might want to use your own logic.

Upvotes: 1

Related Questions