ajax如何上传文件
PHP:
<?php /** * Created by PhpStorm. * User: DELL * Date: 2017/11/23 * Time: 10:57 */ header("Access-Control-Allow-Origin:*"); // 响应类型 header('Access-Control-Allow-Methods:POST'); // 响应头设置 header('Access-Control-Allow-Headers:x-requested-with, content-type'); header("Content-type: text/html; charset=utf-8"); $file = $_FILES["file"]; $name = iconv('utf-8', 'gb2312', "upload/" . $file["name"]); move_uploaded_file($file['tmp_name'], $name); move_uploaded_file($file['tmp_name'], "upload/" . $file["name"]); echo $file["name"]; die();
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"> <title>Title</title> <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> </head> <body> <input type="file" id="fileS" name="file" accept="image/*"> <button>提交</button> </body> <script> $(() => { $("button").click(() => { let formdata = new FormData(); formdata.append('file', $("#fileS")[0].files[0]); $.ajax({ url: "./file_updata.php", type: "post", data: formdata, contentType: false, processData: false, mimeType: "multipart/form-data", success: function (data) { console.log(data) }, error: function (error) { console.log("error", error) } } ) }) }) </script> </html>