2

I have an empty file input field on a page that I would like to populate with a file that already exists on the page using jQuery.

For example, I have the following link:

<a href="download.pdf" class="file">Download Me</a>

And the following form:

<form>
     <input type="file" value="">
     <input type="submit" value="">
</form>

I would like to use jQuery to take the href of the link, and then assign it to the file upload. I could easily start this by assigning a variable to the href like so:

var download = $("a.file").attr("href");

But then how would I go about assigning the file input's upload with this variable?

JCHASE11
  • 3,901
  • 19
  • 69
  • 132
  • Well, the path to the file on the web is different from the path of the file that the user would be uploading (it would actually point to the user's temporary internet files). I'd suggest in this case removing the file input (or giving it a different name or removing it's name) and passing the url with a hidden input. – Kevin B May 01 '13 at 19:54
  • `enctype="multipart/form-data"` must be one of your friends ... Does this looks like something you want to do? http://stackoverflow.com/questions/15259632/upload-image-as-base64-with-jquery-ajax – Tim Vermaelen May 01 '13 at 19:56
  • It seems to be a bit more complex that I thought it would be. @Kevin - I could pass the URL, but I want this to send with a file attachment versus a link. – JCHASE11 May 01 '13 at 20:04
  • @TimVermaelen - I will look into the other answer and see if it is feasible – JCHASE11 May 01 '13 at 20:04
  • @TimVermaelen does this need to be encoded as base64 to send a file attachment? – JCHASE11 May 01 '13 at 20:05

1 Answers1

2

From what I understand what you're trying to do is "using the form tag" to upload file inputs. And you populate the inputs by your links.

HTML

what you enable on the form: http://www.w3.org/TR/html401/types.html#type-content-type

<form method="post" enctype="multipart/form-data">
    <input type="file" value="">
     <input type="submit" value="">
</form>

jQuery

You can send them now with jQuery into an AJAX call

/* untested code */
$(function(){
    var uploads = [],
        form = $("form input").eq(0),
        files = $("a.file").prop("href"),
        len = files.length;

    for (var i = 0; i < len; i += 1){
        // inc. validate files
        // inc. validate form data
        // inc. encryption
        form.prop("src", files[i]);
        uploads.push(form);
    }

    // upload form options.data = form
    // http://api.jquery.com/jQuery.ajax/
    $.ajax(options);
});

Now from what I understand a saver way would be to encrypt what you send, which makes sense security wise.

You don't have to "use encryption" to test it out. See how it goes from there. upload multiple images with jquery ajax and process them with php

Community
  • 1
  • 1
Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39