简体   繁体   English

Laravel:Base64图片未上传

[英]Laravel: Base64 Image not Uploading

Using Laravel and PHP, I am trying to add a photo to a database. 我正在尝试使用Laravel和PHP将照片添加到数据库中。 This database only takes base64 images. 该数据库仅获取base64图像。

I take a given file, verify that it's an image type (png, jpg, etc.) and try to encode it as a base64 image. 我获取一个给定的文件,确认它是图像类型(png,jpg等),然后尝试将其编码为base64图像。 Then I try to upload it to the database with other details about the object. 然后,我尝试将其与有关该对象的其他详细信息一起上载到数据库。

However, this isn't working. 但是,这不起作用。 Instead I am told of a data type mismatch: 相反,我被告知数据类型不匹配:

SQLSTATE[HY000]: General error: 20018 Implicit conversion from data type varchar(max) to varbinary(max) is not allowed. SQLSTATE [HY000]:常规错误:20018不允许从数据类型varchar(max)隐式转换为varbinary(max)。 Use the CONVERT function to run this query. 使用CONVERT函数运行此查询。 [20018] (severity 16) [20018](严重性16)

My code absolutely works when I remove the 'photo' value from the insertion. 当我从插入中删除“照片”值时,我的代码绝对有效。 So I'm wondering what it is that could be the problem with what I'm doing. 所以我想知道我正在做的事情可能是什么问题。

See below my laravel controller function. 参见下面我的laravel控制器功能。

public function addStudent(Request $request) {
    $courses = [1, 2, 3, 4, 5];
    $statuses = [1,2,3,4];

    $validated = Validator::make($request->all(), [
      "submit"      => "required",
      "student_id"  => ["required", "integer", "regex:/^[0-9]+$/"],
      "forename"    => ["required", "regex: /^[a-zA-Z’'. -]+$/"],
      "surname"     => ["required", "regex: /^[a-zA-Z’'. -]+$/"],
      "course_id"   => ["required", Rule::in([1, 2, 3, 4, 5]) ],
      "status_id"   => ["required", Rule::in([1, 2, 3, 4]) ],
      /*Image validation done here: must be of the types below
      Since this part passes, I know I am working with an image */
      "photo"       => "required|image|file:jpeg,png,jpg,gif,svg|max:2048"
]);
$errors = $validated->errors();
if($validated->fails()) {
  return redirect()->back()->withInput($request->all())->withErrors($errors);
}
$data = $request->all();

/* Here I try to encode the image as base64 */
if ($request->hasFile("photo")) {
  if($request->file("photo")->isValid()) {
    $file = $request->file('photo');
    $image = base64_encode($file);
    $image = base64_encode(file_get_contents($request->file('photo')));
    if (!($image)) {
      echo "<h3>Image null!</h3>";
    }
  }
} else {
  echo "<h3>Request doesn't have photo</h3>";
}
/*Try to upload values to database, return errors if fail */
try {
  $insert =
  DB::table('CCEAGpoc.dbo.Student')->insert([
    ['student_id'  => $data['student_id'],
    'forename'    => $data['forename'],
    'surname'     => $data['surname'],
    'course_id'   => $data['course_id'],
    'photo'       => $image,
    'status_id'   => $data['status_id']]
  ]);
  return view('success');
} catch (Exception $ex) { 
  return redirect()->back()->withInput($request->all())->withErrors($errors);
}

For full clarity, my form looks like the following: 为了清楚起见,我的表单如下所示:

<form action="submitAdd" method="post" class="form-inline" enctype="multipart/form-data">
  @csrf
  ...
  <div class="form-group">
      <label for="photo">Photo: </label>
        <input type="file" name="photo" />
  </div>

  <div class="form-group">
    <input type="submit" name="submit" value="Add Student" />
  </div>
</form>

I am honestly not sure what it is about the above that is causing the error. 老实说,我不确定导致错误的原因是什么。 If anyone could help, I'd be hugely thankful. 如果有人可以提供帮助,我将非常感激。

You must decode your base64 string to binary prior to insert it onto varbinary field, as it will accept only binary data. 您必须将base64字符串解码为二进制,然后才能将其插入varbinary字段,因为它将仅接受binary数据。

The base64 permits a safe binary file transmission, but it is not a valid binary value for mssql varbinary, as it is a string type. base64允许安全的二进制文件传输,但是它不是mssql varbinary的有效二进制值,因为它是字符串类型。

DECLARE @string varchar(20)

SET @string = 'Hello World'

SELECT CONVERT(varbinary, @string)

Also, if your are actually using mssql, you should add mssql tag to your question accordingly, there a lot of people with a lot of mssql skills out there (mssql its not my typical day to day database, my knowledge of it is seriously limitated) that are missing your question. 另外,如果您实际使用的是mssql,则应在问题中相应地添加mssql标记,那里有很多掌握mssql技能的人(mssql不是我日常的典型数据库,我对此的认识受到严重限制)遗漏了您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM