在PHP中获取临时上传的带有图片扩展名的文件路径

9

我有一个表单,允许用户上传图像文件。

<div id="imageDiv">
             Image Path : <input class="imageOption" type="file" id= "uploadImageFile" name="uploadImageFile"  >
             </div>

问题出现在我试图从临时文件夹中获取路径时。在处理请求后,我将不再需要图像文件。当我尝试使用以下内容获取路径时出现问题:
$imagePath =  $_FILES['uploadImageFile']['tmp_name'];

路径看起来像 C:\wamp\tmp\phpA123.tmp. 我使用的 API 要求上传图像时路径有扩展名,例如C:\wamp\tmp\image.png 我找不到其他方法除非我想把这些图片复制到其他上传文件夹并使用它。 我不希望这些图片被记录在服务器上。
谢谢
2个回答

20

了解具体使用的API会很有帮助,但是任何良好编写的文件存储API都不应该依赖于上传文件名来存储文件。您应该能够在API中使用临时文件内容,并单独指定文件名。

L5 中:

// Get the UploadedFile object
$file = Request::file('uploadImageFile');

// You can store this but should validate it to avoid conflicts
$original_name = $file->getClientOriginalName();

// This would be used for the payload
$file_path = $file->getPathName();

// Example S3 API upload
$s3client->putObject([
    'Key' => $original_name, // This will overwrite any other files with same name
    'SourceFile' => $file_path,
    'Bucket' => 'bucket_name'
]);

谢谢,我明白你的意思是先分割再组合。我使用的API不是用于文件存储,而是用于向客户发送图像/视频。$w->sendMessageImage($destination, $imagePath)是其中一种方法,我需要从表单中获取该文件的路径($imagePath)。我正在寻找比获取文件名$fileName = Input::file('uploadImageFile')->getClientOriginalName();并将其存储到文件夹中并获取路径$imagePath = Input::file('uploadImageFile')->move($destinationPath, $fileName);更好的解决方案。 - user3491917
谢谢,伙计,运行良好。$result = $s3->putObject(array( 'Bucket' => 'safezone-s3-bucket', 'Key' => 'test.jpg', 'SourceFile' => $image->getPathname() )); 但是图片没有在浏览器中显示,而是强制下载。如何解决? - stackflow
在返回内容之前,您可能需要设置头部。$response->header('Content-Type', 'image/jpeg'); - chrisboustead
这对于我很有帮助。谢谢。 - LetsCMS Pvt Ltd

6
如果你想要在Laravel中获得与以下代码相同的输出 - $imagePath = $_FILES['uploadImageFile']['tmp_name']; 你可以像@cdbconcepts所描述的那样执行以下操作 - $file = Request::file('uploadImageFile'); $imagePath = $file->getPathName()

如果$file = Request::file('uploadImageFile');出现错误,那么你应该使用$file = Input::file('uploadImageFile'); - Ashwani Panwar
是的,我同意你的看法,@AshwaniPanwar。 - Sachin Vairagi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接