Upload an image with jquery ajax with a duplicate-able input

天大地大妈咪最大 提交于 2019-12-23 07:07:14

问题


UPDATE: I have almost solved this problem, please see Jquery form no submission to IE7 and IE8 i just need to sort ot ie7 and ie8,

I have been using THIS plugin to upload files as an email attachment, i have gotten it to the point where it actually works, the only problem is it currently uses this to submit:

jQuery.ajax({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.css("width", percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.css("width", percentVal)
        percent.html(percentVal);
        //console.log(percentVal, position, total);
    },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
}); 

And the form i need to add it to, uses this to submit:

jQuery.ajax({
        type: "POST",
        url: "mail.php",
        dataType: "json",
        data: {parameters: jsonData}
    });

How would i make the plugin work with my form of submission?

Here's the JSFIDDLE for the current working upload form.

and then the form i need to combine the working one with JSFIDDLE (i have shortened it to only the upload fields, but there is a bunch of other information)

Also here's the php send function:

<?php
    function printMember($member) {
        foreach($member as $key=>$value) {
            //Fill the aux string first
            $str.= "$key : $value <br />";
        }
        //string that will be added to $msg variable inside the loop
        return $str;
    }

    $json = $_POST['parameters'];
    $json_string = stripslashes($json);
    $data = json_decode($json_string, true);
    $depCount = count($data["dependants"]);

    $msg .= "<h2>Main member data:</h2>";
    $msg .= printMember($data["mainmember"]);
    $msg .= "<h2>There are $depCount Dependants</h2>";

    foreach ($data["dependants"] as $index => $dependant) {
       $msg .= "<h2>Dependant $index</h2>";
       $msg .= printMember($dependant);
    }

    $strTo = "dawid@jamfactory.co.za";
    $strSubject = "Image Testing";
    $strMessage = nl2br($msg);

    //*** Uniqid Session ***//
    $strSid = md5(uniqid(time()));

    $strHeader = "";
    $strHeader .= "From: Dawid<test@testme.co.za>\nReply-To:test@testme.co.za";

    $strHeader .= "MIME-Version: 1.0\n";
    $strHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
    $strHeader .= "This is a multi-part message in MIME format.\n";

    $strHeader .= "--".$strSid."\n";
    $strHeader .= "Content-type: text/html; charset=utf-8\n";
    $strHeader .= "Content-Transfer-Encoding: 7bit\n\n";
    $strHeader .= $strMessage."\n\n";

    //*** Attachment ***//
    $count = 0;
    foreach($_FILES['myfile']['name'] as $filename)
    {
        $temp = $_FILES['myfile']['tmp_name'][$count];
        $strFilesName = $filename;
        $strContent = chunk_split(base64_encode(file_get_contents($temp))); 
        $strHeader .= "--".$strSid."\n";
        $strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n"; 
        $strHeader .= "Content-Transfer-Encoding: base64\n";
        $strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
        $strHeader .= $strContent."\n\n";
        $count++;
    }


    $flgSend = @mail($strTo,$strSubject,null,$strHeader);  // @ = No Show Error //

    if($flgSend)
    {
        echo "Mail send completed.";
    }
    else
    {
        echo "Cannot send mail.";
    }
?>

If anyone doesn't fully understand the question, I will try here to even further explain it:

I have duplicate-able fields that on submit the information gets put into a JSON array and then gets parsed to an email by PHP, what i was trying to do is have a file field where images get uploaded and sent with the email, but after researching a lot on the web I found that this is not possible with ajax so I found THIS plugin that actually works and now i am just trying to combine it with my original form


回答1:


I don't know if this is suitable for your need or not, but I have used Andrew Valums file-uploader to achieve same result.

It can upload multiple files, even have drag and drop support, but its pure javascript not jQuery, but on the other hand, Ray Nicholus has forked Valums code to a jQuery plugin.

My experience is with Valums version, and it works side by side with jQuery without problem. The only problem is you have to interact with it in basic javascript style.

My implementation of upload is like this:

  1. provide an interface to upload files to server
  2. make file-uploader to upload to a certain folder on server, and return the name and path of the file on server (usually "upload folder"/"file name") so you can store that in a hidden element for the form
  3. when user save their data, only save the path to the file (obtained from step 2) into database

note: with this, you don't need to duplicate any input form for file upload, as you can upload as many file as you like, as long as your server can handle it ofcourse ;)

https://github.com/valums/file-uploader




回答2:


So if I understand it correctly, you want to attach some custom data to file upload. Is it correct?

So if you do not want to modify jQuery plugin you are using, I would add some hidden fields into form and put that custom data into them just before submit. Then plugin should pick them up and send together with files.




回答3:


solved the issue..

It was as simple as adding method="post" action="http://globalgeorgia.co.za/modules/mod_appform/js/mail.php" and then also type="submit" to the submit function and it works perfectly in IE 7 and IE 8 and then also this:

if (isValid) {
    getValues();
    var jsonData = JSON.stringify(result);  

    (function() {
    var bar = jQuery('.bar');
    var percent = jQuery('.percent');
    var status = jQuery('#status');
    jQuery('#spinner').html('<img src="http://globalgeorgia.co.za/modules/mod_appform/js/ajax-loader.gif" />');

    jQuery('#app_form').ajaxForm({
        type: "POST",
        url: "http://globalgeorgia.co.za/modules/mod_appform/js/mail.php",
        dataType: "json",
        //iframe: true,
        data: {parameters: jsonData},
        beforeSend: function() {
            status.empty();
            jQuery('#spinner').html();
            var percentVal = '0%';
            bar.css("width", percentVal)
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.css("width", percentVal)
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
            jQuery('#spinner').html("sent");
        }
    }); 

    })();   
} 

solved the sending issue, thanks for everyone's help.




回答4:


what is the need of getting full local file path. To handle uploaded files, you should not need to know the full file path.Browser takes this job on its own.

please have a look here , you will surely got benefited with this link

  • how to get the file path from html input form in firefox



回答5:


I dont know about PHP just add following to post data. pass parameters to your form

 @{ 
    AjaxOptions options = new AjaxOptions{ 
    HttpMethod = "Post", 
    url: "mail.php",
    dataType: "json",
    data: {parameters: jsonData}
    UpdateTargetId = "formContent",
    beforeSend: function() {
                       status.empty();
                       var percentVal = '0%';
                       bar.css("width", percentVal)
                       percent.html(percentVal);
                      },
     uploadProgress: function(event, position, total, percentComplete) {
                             var percentVal = percentComplete + '%';
                               bar.css("width", percentVal)
                               percent.html(percentVal);
                              //console.log(percentVal, position, total);
                 },

    OnFailure = "do some thing",
    OnBegin = "ShowProgressBar",
    OnComplete =  function(xhr) {
                     status.html(xhr.responseText);
                         }
   };         
} 

you need to add code in PHP (in MVC3 asp .net we do like this)

@using (Ajax.BeginForm(parameters))
 {
 }


来源:https://stackoverflow.com/questions/14560179/upload-an-image-with-jquery-ajax-with-a-duplicate-able-input

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