如何在上传之前获取文件名并传递给另一个文本输入字段而没有fakepath

时间:2019-06-22 01:28:28

标签: javascript php jquery html file-upload

我想在(服务器上的)文件夹中上载图像,并希望在文件输入选择中获得图像名称,然后将此图像名称传递给另一个没有fakepath的文本输入字段。这是我的代码: 这是文件上传php代码

<?php

if (($_FILES['my_file']['name']!="")){
// Where the file is going to be stored
$target_dir = "upload/";
$file = $_FILES['my_file']['name'];
$path = pathinfo($file);
$filename = $path['filename'];
$ext = $path['extension'];
$temp_name = $_FILES['my_file']['tmp_name'];
$path_filename_ext = $target_dir.$filename.".".$ext;

// Check if file already exists
if (file_exists($path_filename_ext)) {
echo "Sorry, file already exists.";
}else{
move_uploaded_file($temp_name,$path_filename_ext);
echo "Congratulations! File Uploaded Successfully.";
}
}
?>

这是json文件写代码

<?php
$message = '';
$error = '';

if(isset($_POST["submit"]))
{

if(empty($_POST["filename"]))
{
$error = "<label class='text-danger'>some text </label>";
}

else
{
if(file_exists('jasonfile.json'))
{
$current_data = file_get_contents('jasonfile.json');
$array_data  = json_decode($current_data, true);

$item = array

( 
'ImageUrl'        =>     $_POST["filename"]
);
array_unshift($array_data["user"] , $item);

$final_data  = json_encode($array_data);
if(file_put_contents('jasonfile.json', $final_data)){
}}
else{
$error = 'JSON File not exits';
}}}
?>

这是我的表单html代码 我想获取图像文件名并将其作为值传递给第二个文本输入字段

<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container" style="width:500px;">
<h3 align="center">Upload YOUR file in folder</h3>
<form action = "?" method="post" enctype ="multipart/form-data">
<?php

?>

<form name="form" method="post" enctype="multipart/form-data" >
<input type="file" name="my_file" onchange="this.form.filename.value = this.value" /> 
<input type="text" name="filename" />
<input type="submit" name="submit" value="Upload"/>
</form>


</form>
</div>
</body>
</html>

预先感谢:)

1 个答案:

答案 0 :(得分:1)

您可以实现iput文件的change事件并获取e.target.files[0].name;

$('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        $('[name=filename]').val(fileName.replace(/C:\\fakepath\\/i, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="form" method="post" enctype="multipart/form-data" >
<input type="file" name="my_file" onchange="this.form.filename.value = this.value" /> 
<input type="text" name="filename" />
<input type="submit" name="submit" value="Upload"/>
</form>