【问题标题】:How do I set my JSON image to url format?如何将我的 JSON 图像设置为 url 格式?
【发布时间】:2020-04-20 12:02:27
【问题描述】:

我想问。如何将我的 json 图片设置为 url 格式。

我有这样的代码来存储我的图像:

public function store(Request $request)
    {

        if ($request->hasFile('objek_pict')) {
            $filePic   = $request->file('objek_pict');
            $extension = $filePic->getClientOriginalExtension();
            $fileName  = date('m-d-Y_', time()) . $request->nama_objek;
            // $filePic->move('/uluwatu_image/', $fileName . '.' . $extension, file_get_contents($request->file('objek_pict')->getRealPath()));
            $filePic->move('uluwatu_image/', $fileName . '.' . $extension);
        }

        $new_objek = new ObjekTable();
        $new_objek->nama_objek = $request->nama_objek;
        $new_objek->objek_lat = $request->objek_lat;
        $new_objek->objek_lng = $request->objek_lng;
        $new_objek->objek_pict = 'uluwatu_image/' . $fileName . '.' . $extension;
        $new_objek->objek_deskripsi = $request->objek_deskripsi;
        $new_objek->save();

        return redirect('masterdata')->with('success', 'Data Berhasil Ditambah');
    }

这就是我获取 json 数据的方式 公共函数getDatajson(请求$请求) {

    $lokasi = ObjekTable::select('id_objek as id', 'nama_objek as name', 'objek_lat as latitude', 'objek_lng as longitude', 'objek_deskripsi as description', 'objek_pict as image_object')->get();
}

这是我的 json 数据链接:https://aruluwatu.000webhostapp.com/api/json

这是图片:https://i.stack.imgur.com/aff6L.jpg

我想让我的 json 图像显示这样的 url 路径: https://aruluwatu.000webhostapp.com/uluwatu_image/04-15-2020_Rumah.jpg

*uluwatu_image/04-15-2020_Rumah.jpg(我保存的图片)

【问题讨论】:

    标签: json laravel


    【解决方案1】:

    您可以使用 Eloquent Accessors 来实现这一点,它允许您定义自定义属性

    在模型ObjekTable中定义附加属性:

    protected $appends = ['image_url'];
    

    然后在同一模型上设置 value image_url 属性:

    public function getImageUrlAttribute()
    {
       return url(Storage::url( $this->objek_pict ));
    }
    

    现在您在模型即时获得新属性 image_url 包含完整的图像 url

    【讨论】:

    • 我在我的模型上设置了 getImageUrlAttribute() 对吗?还是在我的控制器中?
    • 在你的模型'ObjekTable'上
    • 和“image_url”我更改为我的网络服务链接?像这样 protected $appends = ['aruluwatu.000webhostapp.com'];
    • 我试过了,但没有找到路径。这是输出: [{"id":119,"name":"Ahayy","latitude":-8.80335,"longitude":115.1542,"description":"yeaa","images":"uluwatu_image\/ 04-21-2020_Ahayy.JPG","image_url":"https:\/\/aruluwatu.000webhostapp.com\/storage"}]
    • 这就是我尝试的,就像你说的:pastebin.com/jVxhXNvM
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多