上传文件并使用formData()将其附加到电子邮件

时间:2013-01-07 10:06:18

标签: php jquery post multipartform-data

  

可能重复:
  submit success but upload not work at combine form

我正在使用“仅提交文件”标题下的here代码。代码非常简单,但是当我在console.log中找到“文件”时,它没有位置,webkitrelativepath就是“”,我可以在提交时看到文件名,大小等。我需要将它发布到我的feedback.php文件并将其附加到那里的电子邮件,但我不知道如何从formData中取出文件并将其上传到我的上传文件夹,以便我可以邮件...

感谢。

编辑:

我目前使用的是什么代码:

var fileInput = document.getElementById('file-upload-field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
console.log(file);

$.ajax({
  url: baseUrl + "feedback.php",
  data: file,
  cache: false,
  contentType: false,
  processData: false,
  type: 'POST',
  success: function(file){
    alert(file);
  }
});

和我的feedback.php

  foreach($_FILES as $file){
    $target_path = "uploads/";
    $target_path = $target_path .basename($file['name']);



if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}
else {
 echo "there was an error";
}
$mail->AddAttachment($target_path);

}

这不会在任何地方上传或附加任何文件......

1 个答案:

答案 0 :(得分:0)

只需使用

上传文件即可
move_uploaded_file(string $filename , string $destination );

而不是邮件作为附件如下:

require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->Host = 'smtp_host';      
$mail->Port = 'smtp_port';
$mail->SMTPAuth = true;         
$mail->Username = 'smtp_user';  // SMTP username
$mail->Password = 'smtp_pass';  // SMTP password
$mail->From = "from@abc.ocm";
$mail->FromName = "fromName";
$mail->AddAddress($email);
$mail->Subject = "Your subject line";
$mail->AddAttachment($source, $fileName);
$mail->Body = "Your Message";

// Send the email.
if(!$mail->Send())
    $message = "Displya some error.";

}