最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Upload an image with jquery ajax with a duplicate-able input - Stack Overflow

programmeradmin0浏览0评论

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 = "[email protected]";
    $strSubject = "Image Testing";
    $strMessage = nl2br($msg);

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

    $strHeader = "";
    $strHeader .= "From: Dawid<[email protected]>\nReply-To:[email protected]";

    $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

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 = "[email protected]";
    $strSubject = "Image Testing";
    $strMessage = nl2br($msg);

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

    $strHeader = "";
    $strHeader .= "From: Dawid<[email protected]>\nReply-To:[email protected]";

    $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

Share Improve this question edited Sep 4, 2019 at 12:16 ROMANIA_engineer 56.7k30 gold badges208 silver badges205 bronze badges asked Jan 28, 2013 at 10:40 user1278673user1278673 1
  • I think the question is not focused enough. You write something about images but then it's no very clear what exactly is the problem. Also it might be a good idea to isolate the problematic code rather than showing it entirely. – Roy Commented Jan 30, 2013 at 11:15
Add a comment  | 

5 Answers 5

Reset to default 4 +25

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

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.

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.

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

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))
 {
 }
发布评论

评论列表(0)

  1. 暂无评论