现在是可能的。
这就是我做到这一点的方式。首先,我使用 Uploadable Behavior 来处理从以下位置上传的文件:https ://github.com/cakemanager/cakephp-utils
模型:
$this->addBehavior('Utils.Uploadable', [
'file' => [
'removeFileOnUpdate' => false,
'field' => 'file_tmp',
'path' => dirname(ROOT).'{DS}invoices{DS}',
'fileName' => '{field}'
]
]);
控制器:
public function ajaxInvoice() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$this->Invoices->deleteAll(['order_id' => $this->request->data['order_id']]);
$invoice = $this->Invoices->newEntity();
$invoice->order_id = $this->request->data['order_id'];
$invoice->file_tmp = $this->request->data['file']['name'];
$invoice = $this->Invoices->patchEntity($invoice, $this->request->getData());
$this->Invoices->save($invoice);
$this->response->body($invoice);
}
}
模板:
<?php use Cake\Routing\Router; ?>
<input type="file" class="upload<?= $id ?> hidden"><a data-id="<?= $id ?>" class="upload">Upload</a>
<script type = "text/javascript" > $(document).ready(function() {
$('.upload').on('click', function() {
var id = $(this).attr('data-id');
$('.upload' + id + '').click();
$('.upload' + id + '').change(function(e) {
e.stopImmediatePropagation();
var form = new FormData();
form.append('file', $(this)[0].files[0]);
form.append('order_id', id);
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller ' => 'Invoices ', 'action ' => 'ajaxInvoice ')); ?>',
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data, status, xhr) {
var response = JSON.parse(xhr.responseText);
},
});
});
});
});
</script>