要求:
我必须在PHP文件中提交一个具有文件类型输入的表单。我需要jQuery ajax发布这个文本文件,让我们说processFile.php
processFile.php将此文本文件作为输入,处理后将返回一个我想在客户端下载的csv文件。
我见过很多帖子,但没有什么可以帮助我。
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery的:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
我已尝试过网上提供的数百种解决方案,但都没有。
答案 0 :(得分:1)
我在这里提供完整的工作示例:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<a href='#' id="tmpcsv" style="display:none">Download</a>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
尝试上传任何文件。 这对你有用吗?