You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Livewire通过HTTP上传图片至API时文件类型异常问题

解决Laravel Livewire图片上传API后存储为TXT格式的问题

问题分析

上传图片被存为.txt格式,核心原因有两个:

  1. Http::attach中指定的文件Content-Type错误,应使用图片对应MIME类型而非multipart/form-data
  2. API端用store()方法时未显式保留原扩展名,Laravel无法识别图片类型时默认用.txt

修复步骤

1. 修正Livewire端的Http请求代码

调整attach方法的参数,确保传入正确的文件内容、原文件名和图片MIME类型:

$response = Http::attach(
    'photo',
    file_get_contents($this->photo->getRealPath()),
    $this->photo->getClientOriginalName(),
    ['Content-Type' => $this->photo->getClientMimeType()]
)->post('http://localhost:8001/api/v1/client/profile/1', [
    '_method' => 'PUT',
]);
  • 用file_get_contents($this->photo->getRealPath())获取真实文件内容
  • 用$this->photo->getClientOriginalName()保留原文件名(含扩展名)
  • 用$this->photo->getClientMimeType()自动匹配图片正确的MIME类型

2. 修正API端的文件存储代码

使用storeAs()方法显式指定带扩展名的文件名,避免默认格式错误:

$file = $request->file('photo');
$fileName = uniqid() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('photo', $fileName, 'public');

return response()->json([
    'message' => 'Your API handler executed successfully',
    'data' => $path,
]);

额外验证

确保Livewire组件正确引入文件上传特性:

use Livewire\WithFileUploads;

class Profile extends Component
{
    use WithFileUploads;

    public $photo;

    // 其他业务逻辑
}

内容的提问来源于stack exchange,提问作者imado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 01:10:02