Home  >  Article  >  Backend Development  >  HTML uploads image data to the server, and PHP receives and saves the image.

HTML uploads image data to the server, and PHP receives and saves the image.

WBOY
WBOYOriginal
2016-08-08 09:26:351541browse




Many times, we need to save the image data on the web or the images in the canvas to the server. HTML5 already provides available interfaces.


The toDataURL method of Canvas can export the canvas data on the canvas into a string format. We just need to transmit the string to the server again.

What should I do if the picture has an img tag?

Very simply, canvas provides the drawImage method, which is used to draw img or other canvas data onto your own canvas.

Next, let's look at the client code:

var cc = window.document.getElementById("egretCanvas");
var cc2 = document.createElement("canvas");
cc2.setAttribute("width", "320");
cc2.setAttribute("height", "514");
var ctx = cc2.getContext("2d");
ctx.drawImage(cc, 0, 0, 320, 514);
var imgdata: string = cc2["toDataURL"]();


The exported string contains the prefix "data:image/png;base64," so we need to remove this prefix

imgdata = imgdata.substring(22); 

Then pass the string to the server. Here we choose to use the php language to receive the data and save the image.


$imgurl = str_replace(' ', '+', $_REQUEST['image']);
First replace the spaces in the string with "+" signs.


$savePath = "../images/123.png";
$image = base64_decode($image);
file_put_contents($savePath,$image);

After php gets the data, it needs to be base64 decoded before it can be saved as an image.



The above introduces how HTML uploads image data to the server, and PHP receives and saves images, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn