gpt4 book ai didi

javascript - PHP中的Ajax上传文件

转载 作者:行者123 更新时间:2023-12-02 16:12:02 25 4
gpt4 key购买 nike

在我的 PHP 应用程序中,我有一些由 AJAX 生成的内容,其中表单具有文件输入。

此表单位于 Bootstrap Modal 中。我将一些数据写入输入并使用 jQuery 文件上传插件 5.26 上传文件,它工作正常。

我关闭模式并通过单击另一个列表元素异步加载相同的内容。

我做了和以前一样的操作,但出现错误:4;

No file was uploaded.

我使用了相同的操作、相同的模式和表单,唯一的区别是我使用 AJAX 渲染它两次。谁能解释一下如何修复此错误以及如何上传第二个文件?

我想补充一点,文本输入中的数据已更改,但 $_FILES 是空数组。

另一个信息是,当我首先渲染 View 时,我可以上传文件、关闭模式并上传第二个文件。

问题是当我第二次渲染此 View 并尝试上传文件时。

AJAX 发送 POST 并获取 View :

 $.ajax({
type: "POST",
url: "/ksiazka/pobierz-partial",
dataType : 'json',
data: {
id: idObiektu,
template: template,
typ: typObiektu,
fmodel: fmodel
},
success: function(data)
{
$('#ksiazka-tresc').html(data.html);
}
});

渲染 View :

public function pobierzPartialAction()
{
$request = $this->getRequest();
if ($request->isPost()) {

$id = $request->getPost('id');
$templatka = $request->getPost('template');
$typ = $request->getPost('typ');
$fmodel = $request->getPost('fmodel');

/* @var $wartosciDoTemplatki \Obiekty\Model\Ommost */
$wartosciDoTemplatki = $this->pobierzWartosciDoTemplatki($templatka, $id, $typ, $fmodel);

$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('template/' . $templatka)
->setVariables(array(
'wartosci' => $wartosciDoTemplatki
));

$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);


$jsonObject = \Zend\Json\Json::encode(array(
'html' => $htmlOutput
), true);
echo $jsonObject;
return $this->response;
}
}

查看:

<div class="row" style="padding-bottom: 5px">              

<div class="col-sm-6" id="ksiazka-save-table-alert">
<div class="alert alert-success text-center" role="alert" style="padding: 4px; margin-bottom: 0; display: none">Pomyślnie zapisano</div>
</div>
<div class="col-sm-6 text-right">
<img src="/img/30-load.gif" alt="spinner" class="ksiazka-table-spinner" style="display: none">
<div class="btn-group btn-group-sm" role="group">
<a class="btn btn-primary ksiazka-add-photo" data-toggle="tooltip" data-placement="top" title="Dodaj rekord"><i class="fa fa-plus"></i></a>
<a class="btn btn-danger karta-delete-row" data-toggle="tooltip" data-placement="top" title="Usuń rekord"><i class="fa fa-minus"></i></a>
<a class="btn btn-success karta-save-row" data-toggle="tooltip" data-placement="top" title="Zapisz zmiany"><i class="fa fa-check"></i></a>
</div>
</div>

模态:

<div class="modal fade bs-example-modal-lg" tabindex="-1" aria-hidden="true" id="ksiazkaFileUpload"><div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Dodawanie zdjęcia</h4>
</div>
<div class="modal-body" style="min-height: 450px" id="hide-spinner">
<div class="row">
<div class="col-sm-12">
<form id="upload" method="post" action="/ksiazka/upload-file" enctype="multipart/form-data">
<input type="hidden" name="model" value="<?php echo $wartosci['model-pliki'] ?>" />
<input type="hidden" name="tabela" value="<?php echo $wartosci['tabela-pliki'] ?>" />
<input type="hidden" name="MASTER_ID" />
<?php if(isset($wartosci['OM_ID'])): ?>
<input type="hidden" name="OM_ID" value="<?php echo $wartosci['OM_ID'] ?>" />
<?php endif ?>

<label for="NR">NR</label>
<input type="text" class="form-control" name="NR" />
<label for="OPIS">Opis</label>
<input type="text" class="form-control" name="OPIS" />
<div id="drop" style="margin-top: 10px">
<input type="file" name="upl" />
<a href="#" class="file btn btn-primary pull-right disabled"><i class="fa fa-plus"></i> Dodaj</a>

</div>
<ul style="margin-top: 20px">
The file uploads will be shown here
</ul>
</form>
</div>
</div>
</div>
</div>

上传文件操作:

public function uploadFileAction()
{
$allowed = array('png', 'jpg', 'gif','zip', 'txt', 'rtf');

var_dump($_FILES, $_POST);

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0)
{

$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}

$file = file_get_contents($_FILES['upl']['tmp_name']);

$idTypu = 2;

$values = $_POST;

$model = $values['model'];
$tabela = $values['tabela'];

$values['ID_TYPU_PLIKU'] = $idTypu;

$values['PLIK'] = 'empty_blob()';
$values['OPIS'] = "'". $values['OPIS'] . "'";
$values['NR'] = "'". $values['NR'] . "'";

$values['NAZWA_PLIKU'] = "'". $_FILES['upl']['name'] . "'";

unset( $values['model']);
unset( $values['tabela']);

$session = new \Zend\Session\Container('namespace');
$zasobId = $session->item;

$zasob = $this->getZasobyTable()->zwrocSchematPoId($zasobId);

$fun = 'get' . $model . 'Table';

$this->$fun()->saveUploadedFile($file, $values, $tabela, $zasob);
echo 'ok';
exit;
}

echo '{"status":"error"}';
exit;
}

JS脚本:

var ul = $('#upload ul');

$('.file').click(function(e){
e.preventDefault();

// Simulate a click on the file input button
// to show the file browser dialog

$(this).parent().find('input').click();
});

// Initialize the jQuery File Upload plugin
$('#upload').fileupload({

// This element will accept file drag/drop uploading
dropZone: $('#drop'),
pasteZone: $(document),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {

var tpl = $('<li class="working"><input type="text" value="0" data-width="20" data-height="20"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');

// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<b>' + formatFileSize(data.files[0].size) + '</b>');

// Add the HTML to the UL element
data.context = tpl.appendTo(ul);

// Initialize the knob plugin
tpl.find('input').knob();

// Listen for clicks on the cancel icon
tpl.find('span').click(function(){

if(tpl.hasClass('working')){
jqXHR.abort();
}

tpl.fadeOut(function(){
tpl.remove();
});

});

// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},

progress: function(e, data){

// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);

// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();

if(progress == 100){
data.context.removeClass('working');
}
},

fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
},

done: function (e, data) {
}

});

最佳答案

我们还没有任何代码,但 ajax 传输中最常见的错误是它们如何在调用中定义数据。我上传这样的文件:(尝试一下)

      $.ajax({
type: 'post',
url: 'upload.php',
data: new FormData($('form')[0]),
processData: false,
contentType: false,
success: function (result) {
//show a success message or something else
}
});

关于javascript - PHP中的Ajax上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com