我正在尝试通过AJAX将文件(PDF)上传到我的服务器,以便在laravel项目中由php脚本处理。我无法将文件发送到服务器并在服务器上收到。
在网络中,我可以看到POST请求获得200响应,但是它返回'文件不存在' 的响应,这是来自laravel的响应
同样在帖子请求中,请求有效负载包含以下内容
------WebKitFormBoundaryliAmA3wxs0bB32iZ--
请参阅下面的js和html以及php:
HTML
<form enctype="multipart/form-data">
<input type="file" id="cv" name="cv"/>
<button id="file-send">Add</button>
</form>
JS
$('#file-send').bind('click', function () {
$.ajax({
url:"test",
data: new FormData($("#cv")[0]),
type:'POST',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
LARAVEL CODE
public static function uploadingFile(){
if (Input::hasFile('cv'))
{
return "file present";
}
else{
return "file not present";
}
答案 0 :(得分:0)
试试这个:
JS:
$('#file-send').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
腓:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
答案 1 :(得分:0)
尝试使用此插件上传文件
http://malsup.com/jquery/form/#file-upload
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType :'json'
};
$('#file-send').ajaxSubmit(options);
function showRequest()
{
//before uploading file
}
function showResponse()
{
//response after uploading file
}