【问题标题】:PHP Laravel multiple file upload by using two tablesPHP Laravel 多文件上传使用两个表
【发布时间】:2019-10-07 13:58:57
【问题描述】:

我正在构建一个Laravel-nova 应用程序,我有一个<form>,应该可以上传多个文件。所以我必须表 - single_applicationssingle_application_files。所以,当我填写表格时,数据会正确发布,但文件除外,我完全不知道为什么,例如我不知道我做错了什么。

这是刀片模板:

<form method="POST" action="{{ route('application.store') }}">

    <div class="input-group mb-3">
       <input name="name" type="text" class="form-control" placeholder="Name" autocomplete="name" required>
    </div>
    //...and a bunch more
    //...then the file input

    <div class="form-group col">
       <div class="custom-file file">
          <input type="file" class="custom-file-input" id="attachment-1" name="attachment_cv[]" accept=".pdf,.doc,.docx,application/msword,.png,.jpg,.jpeg,.gif">
            <label class="custom-file-label" for="attachment-1">Add File</label>
            <div class="addBtnContainer">
               <a href="#" data-js="add" class="js-addFileField">+ Add</a>
            </div>
       </div>
   </div>
</form>

由于可用性,我不想要&lt;input type="file" multiple /&gt;,而是用户可以点击add,并在jquery 的帮助下,出现另一个文件输入字段。

我的SingleApplication-Model 看起来像这样:

class SingleApplication extends Model
{

    protected $fillable = [
       'avatar', 'name', 'email', 'phone', 'address', 'zipcode', 'city', 
       'education', 'about', 'birthyear', 'job_category', 'status','vehicles', 'worktime', 'clothing'
    ];
}

而我的SingleApplicationFile-Model 看起来像这样

class SingleApplicationFile extends Model
{
   protected $fillable = [
    'attachment_cv', 'files_id', 'attachment_cv_name', 'attachment_cv_size', 'single_applications_id'
   ];
 }

到目前为止一切顺利,所以我确实使用axios 来发布数据,所以看起来是这样的:

 $('#singleApplication button[type="submit"]').click(function(e) {
    e.preventDefault();

    var formData = new FormData();

    formData.append(
        "name",
        $("#singleApplication")
            .find('input[name="name"]')
            .val()
    );
    // ...etc. etc. the same with all other fields

    // HERE I FETCH THE ATTACHMENT FILES
    var attFiles = [];

    $('input[name="attachment_cv[]').each(function() {
        attFiles.push($(this).prop("files")[0]);
    });

    formData.append("attachment_cv", attFiles);


    axios.post($("#singleApplication form").attr("action"), formData)
        .then(response => {
        })
        .catch(error => {
            console.log(error.response.data); // DEBUG
        });

    });

 });

现在涉及到控制器,这就是我认为出现问题的地方。

use App\SingleApplication;
use App\SingleApplicationFile;

class SingleApplicationsController extends Controller
{
   public function store()
   {
    $application = SingleApplication::create([
        'email' => request()->email,
        'name' => request()->name,
        'avatar' => request()->avatar,
        'phone' => request()->phone,
        'address' => request()->address,
        'zipcode' => request()->zipcode,
        'city' => request()->city,
        'birthyear' => request()->birthyear,
        'job_category' => request()->job_category,
        'education' => request()->education,
        'about' => request()->about,
        'vehicles' => request()->vehicles,
        'worktime' => request()->worktime,
        'clothing' => request()->clothing,
        'status' => request()->status,
    ]);


    if (request()->hasFile('attachment_cv')) {

        $files = request()->file('attachment_cv');
        foreach ($files as $file) {
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $filesize = $file->getSize();

            $path = Storage::disk('local')->put('attachments/application_files', request()->file($filename));

            $application_files = SingleApplicationFile::create([
                'files_id' => $application->id,
                'single_application_id' => $application->id,
                'attachment_cv' => $path,
                'attachment_cv_name' => $extension,
                'attachment_cv_size' => $filesize,
            ]);

            new SingleApplicationFile($application_files);

            return response()->json('OK', 200);
        }
    }
}

那么,有人可以告诉我,我做错了什么吗?如前所述,除文件外,所有数据都经过,数据库中的表保持为空。

更新

由于某种原因,请求没有通过该行

  if (request()->hasFile('attachment_cv')) {}

怎么可能?

【问题讨论】:

  • enctype="multipart/form-data" 添加到您的
    without it 文件不会随发布请求一起发送

标签: php mysql laravel laravel-nova


【解决方案1】:

由于您需要上传文件,请在表单中添加enctype="multipart/form-data",我注意到这一行中的request()-&gt;file($filename)

$path = Storage::disk('local')->put('attachments/application_files', request()->file($filename));

您的字段名称是 attachment_cv 而不是 $filename。所以你需要尝试以下方法之一

$name = md5('myfile_'.date('m-d-Y_hia')).'.'.$extension; //This will save a unique file name

$path = Storage::disk('local')->put('attachments/application_files/'.$name, $_FILES['attachment_cv']['name'][$i]);

//根据foreach递增$i

$path = Storage::disk('local')->put('attachments/application_files/'.$name, $filename);

您也可以使用$path = $filename-&gt;store('attachments/application_files'); 这将自动生成一个随机文件名

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2015-01-30
    • 2019-09-30
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多