SoFunction
Updated on 2025-04-04

Upload image instance code

I recently fell in love with using it as a front-end. Yesterday, I encountered a problem when uploading pictures with vue. I finally figured out the code for the relevant part in the last half day.

Front-end part

<div class="form-group">
    <label>Background image</label>
    <input type="file" class="form-control" @change="onFileChange">
 </div>
<div class="form-group" v-if="image">
    <label>Background image预览</label>
    ![](image)
</div>

part

Add in methods

onFileChange(e) {
  var files =  || ;
  if (!)
   return;
   (files[0]);
  },
createImage(file) {
  var image = new Image();
  var reader = new FileReader();
  var vm = this;

   = (e) => {
     = ;
  };
    (file);
},

So how to get it when submitting?

In the submit method, the obtained image format is the image stream format,data:imagebeginning.

How to get it in the backend (I use php)?

Post code directly

$bg = $request->get('image');//Get picture stream$url = explode(',',$bg);
$filename = md5(time().str_random(8)).'.png';//Custom image name$filepath = public_path('image').'/'.$filename;//Image storage path$bgurl = '/image/'.$filename;//Picture url, depending on your background environment, I use laravelfile_put_contents($filepath, base64_decode($url[1]));//Save the image to a custom path

Save $bgurl in the database.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.