首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在php中以变量的形式获取上传文件的相对路径(repost)

如何在php中以变量的形式获取上传文件的相对路径(repost)
EN

Stack Overflow用户
提问于 2017-01-06 19:30:47
回答 1查看 947关注 0票数 0

如何获取上传文件的相对路径?例如,如果我上传test.png,我会得到/ upload /test.png。这是我的HTML:

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jquery Ajax File Upload</title>
</head>
<body>

    <div class="col-sm-6">
        <div class="form-group ">
            <label>Profile image</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-image"></i></span> 
                <input type="text" class="form-control" name="profile_image" autocomplete="off" value="" placeholder="" >
                 <label class="btn btn-default btn-file input-group-addon">
    Browse <input type="file" name="image" style="display: none;" onchange="myFunction()" id="image" >
</label>
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>

        $('#image').change(function(e){
            var file = this.files[0];
            var form = new FormData();
            form.append('image', file);
            $.ajax({
                url : "http://192.168.1.147/upload.php",
                type: "POST",
                cache: false,
                contentType: false,
                processData: false,
                data : form,
                success: function(response){
                    $('.result').html(response.html)
                }
            });
        });

    </script>

            </div>
        </div>
    </div>

</body>
</html>

PHP:

代码语言:javascript
复制
<?php

$file = $_FILES['image'];


/* Allowed file extension */
$allowedExtensions = ["gif", "jpeg", "jpg", "png", "svg"];

$fileExtension = explode(".", $file["name"]);

/* Contains file extension */
$extension = end($fileExtension);

/* Allowed Image types */
$types = ['image/gif', 'image/png', 'image/x-png', 'image/pjpeg', 'image/jpg', 'image/jpeg','image/svg+xml'];

if(in_array(strtolower($file['type']), $types) 
    // Checking for valid image type
    && in_array(strtolower($extension), $allowedExtensions) 
    // Checking for valid file extension
    && !$file["error"] > 0)
    // Checking for errors if any
    { 
    if(move_uploaded_file($file["tmp_name"], 'uploads/'.$file['name'])){
        header('Content-Type: application/json');
        echo json_encode(['html' => /*return uploded file path and name*/ ]);    
        echo $_FILES['upload']['name'];
    }else{
        header('Content-Type: application/json');
        echo json_encode(['html' => 'Unable to move image. Is folder writable?']);    
    }
}else{    
    header('Content-Type: application/json');
    echo json_encode(['html' => 'Please upload only png, jpg images']);
}

?>

代码起作用了,那就是上传文件,但我不知道如何取回路径。路径可能会更改,因为它用于用户配置文件图像,稍后我会将上传路径更改为/$username。如果你只知道如何获得名字,请张贴。提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-06 20:19:18

假设是test1.png$file['name']中有文件的名称

这是程序的一部分,用于将文件保存在特定位置。在本例中,是相对于当前工作目录的文件夹uploads

代码语言:javascript
复制
if(move_uploaded_file($file["tmp_name"], 'uploads/'.$file['name'])){
    header('Content-Type: application/json');
    echo json_encode(['html' =>  
                       /* you might want to output something like */
                          getcwd().'/uploads/'.$file['name']
                        // getcwd()    current working directory
                        // it may be that you need a relative path based on 
                        // where your application lives to generate a url, for example
                        // 'http://your_app_base_url/'.'/uploads/'.$file['name']
                     ]);    
    echo $_FILES['upload']['name']; // this will be empty unless there is a file form field with the name 'upload' 
                                   // compare with $_FILE['image'] above
}else{
    header('Content-Type: application/json');
    echo json_encode(['html' => 'Unable to move image. Is folder writable?']);    
}

如果您想在以后移动该文件,您可以有一个名为profile_pics的目录,并将其移动到该目录中,然后重命名为用户名。

例如:

代码语言:javascript
复制
$oldfilename = $file['name'];

//create a name for the file based on username and uploaded file extension (.jpg/.png)
$newfilename = $username.'_profile.'.pathinfo($oldfilename,PATHINFO_EXTENSION);

//this will rename /move the file from uploads to profile_pics (directory must exist already)
rename('uploads/'.$oldfilename,'profile_pics/'.$newfilename);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41504769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档