我正在构建一个带有上传字段的表单小部件,其中表单数据通过 WordPress REST_API 通过 POST 请求 发送。效果很好,但我无法使用正确的文件名和文件扩展名发送上传文件。目前正在使用临时名称和 .tmp 扩展名发送。
JS Ajax 请求 只是为了举例说明
submitData(form) {
let formData = new FormData(form[0]);
jQuery.ajax({
url: '/wp-json/my-plugin/v1/send_email/',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function () {
// validate fields
},
success: function (response) {
// success actions
},
error: function () {
// build error messages
}
});
return false;
}
通过REST_API接收的文件数据示例
{
"form_fields": {
"name": {
"file": "beatifull-picture.jpeg"
},
"full_path": {
"file": "beatifull-picture.jpeg"
},
"type": {
"file": "image/jpeg"
},
"tmp_name": {
"file": "C:\\Windows\\Temp\\phpD363.tmp"
},
"error": {
"file": 0
},
"size": {
"file": 364006
}
}
}
最后负责将附件添加到 wp_mail()t 的代码:
protected function send_mail($mail_data, $file){
// ..
$attachment = $this->prepare_attachments($file);
$email = wp_mail(
$mail_data['mail_to'],
$mail_data['mail_subject'],
$mail_data['mail_message'],
$mail_data['headers'],
$attachment,
);
}
// KEY FUNCTION
protected function prepare_attachments($files) {
$attachments = [];
// Iterate through the files array to extract attachments
if (isset($files['form_fields']['tmp_name']['file'])) {
$tmp_name = $files['form_fields']['tmp_name']['file'];
$error = $files['form_fields']['error']['file'];
if ($error === UPLOAD_ERR_OK) {
// Log the path of each file
error_log('Attachment: ' . $tmp_name);
$attachments[] = $tmp_name;
}
}
return $attachments;
}
我尝试过几种方法。已尝试获取文件的原始名称而不是临时名称,但文件未附加;在附加之前尝试上传到 WordPress;尝试存储原始名称和扩展名并在之后替换,但到目前为止没有任何效果。
提前致谢,对于长代码深表歉意
使用 wp_handle_upload() 完成了这项工作。问题是,在发送之前仅获取/使用附件数据而不将文件移动到某个位置是行不通的。始终以临时格式/扩展名发送。
<?php
protected function prepare_attachments($files) {
$attachments = [];
// Check if wp_handle_upload is available
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
if (isset($files['form_fields']['tmp_name']['file'])) {
// Populate the file array with the file details
$file = array(
'name' => $files['form_fields']['name']['file'],
'type' => $files['form_fields']['type']['file'],
'tmp_name' => $files['form_fields']['tmp_name']['file'],
'error' => $files['form_fields']['error']['file'],
'size' => $files['form_fields']['size']['file'],
);
// Upload the file to the uploads directory
$upload_result = wp_handle_upload($file, ['test_form' => false]);
if (!isset($upload_result['error'])) {
$attachments[] = $upload_result['file'];
// delete the uploaded file after sending the email
register_shutdown_function('unlink', $upload_result['file']);
} else {
// Log an error if the file could not be moved
error_log('Failed to upload file: ' . $upload_result['error']);
}
}
return $attachments;
}