2016-01-16 64 views
1

我有問題上傳文件,通過苗條的框架3 Slim \ Http \ UploadedFile。Slim Framework 3上傳

我的代碼:

$app->post('/upload', function ($req, $res, $args) { 
    $setting = $this->settings; 
    $uploadPath = $setting['upload']['path']; 
    $file = $req->getUploadedFiles()['img']; 
    $file->moveTo($uploadPath); 
    return $res; 
}); 

結果:

Slim Application Error 
The application could not run because of the following error: 

Details 

Type: RuntimeException 
Message: Error moving uploaded file hss.png to /home/xxx/web/slim3/app/../log 
File: /home/xxx/web/slim3/vendor/slim/slim/Slim/Http/UploadedFile.php 
Line: 237 

回答

4

我已經找到了答案。由於@akrabat

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
     <meta charset="utf-8"> 
 
     <title>Slim 3</title> 
 
     <link rel="stylesheet" href="http://yegor256.github.io/tacit/tacit.min.css"> 
 
    </head> 
 
    <body> 
 
     <h1>Upload a file</h1> 
 
     <form method="POST" action="/upload" enctype="multipart/form-data"> 
 
      <label>Select file to upload:</label> 
 
      <input type="file" name="newfile"> 
 
      <button type="submit">Upload</button> 
 
     </form> 
 
    </body> 
 
</html>

$app->post('/upload', function ($request, $response, $args) { 
 
    $files = $request->getUploadedFiles(); 
 
    if (empty($files['newfile'])) { 
 
     throw new Exception('Expected a newfile'); 
 
    } 
 

 
    $newfile = $files['newfile']; 
 
    // do something with $newfile 
 
});

+0

我已經實現完全一樣,但我仍然無法通過郵遞員上傳文件。總是拋出關鍵字丟失的異常 –

0

使用這個PHP function代替的moveTo功能

+0

我已經找到了https://akrabat.com/psr-7-file-uploads-in-slim-3/ –

0
//localhost store image 

定義( 'pic_root', 「/無功/網絡/ HTML/API /應用/照片」) ; define('pic_image',「http://localhost/api/app/photo」);

$ APP->交的( '/ adduser的',函數($請求,$響應){

$post = $request->getParsedBody(); 

extract($post); 

require 'db_connect.php'; 

$img =" "; 
if($_FILES['photo']['error'] === 0){ 
    $files = $_FILES['photo']; 
    $imgname = $files['name']; 
    move_uploaded_file($files['tmp_name'], pic_image.'/'.$imgname); 
    $img = pic_root.'/'.$imgname; 
} 

$q = "INSERT INTO users (name,phone,taluka,disticts,city,photo) 
    VALUES ('".$name."','".$phone."','".$taluka."','".$disticts."','".$city."','".$img."')"; 

$user = $pdo->query($q); 

$user = array(
       "status" => (bool)$user, 
       "message" => "User Created" 
      ); 
    return $response->withStatus(200) 
     ->withHeader('Content-Type', 'application/json') 
     ->write(json_encode($user,JSON_FORCE_OBJECT));   

});

+1

您可以添加一行或兩行,說明此代碼可以解決問題的程度或與代碼在問題上有多大差異?要獲得正確的代碼展示,可以使用Ctrl + k。 – ImportanceOfBeingErnest