我的代码遇到了问题。我知道我做错了什么,但我不知道是什么。 我有一个照片上传表单,如果它已经不存在则必须创建一个文件夹,并将图片上传到该文件夹。
所以我的问题是我不能同时做两件事 e。 如果该文件夹已经存在,则上传图像,但如果该文件夹不存在,则只创建该文件夹,我必须再次上传该图片进入该文件夹。
这是我的代码。
INDEX.HTML
<form action="" method="post" enctype="multipart/form-data">
<input id="input-image-3" class="file-loading" type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
</form>
<script>
$("#input-image-3").fileinput({
uploadUrl: "upload.php",
allowedFileExtensions: ["jpg","jpeg", "png", "gif"],
maxImageWidth: 100,
maxImageHeight: 100,
resizePreference: 'height',
maxFileCount: 10,
resizeImage: true,
}).on('filepreupload', function() {
$('#kv-success-box').html('');
}).on('fileuploaded', function(event, data) {
$('#kv-success-box').append(data.response.link);
$('#kv-success-modal').modal('show');
});
</script>
upload.php的
<?php
$valid_formats = array("jpg", "png");
$max_file_size = 1024*100; //100 kb
$path = "up/test/"; // Upload directory, later i'll get the name of user
$filename=$file['filename'];
$extension = '.jpg';
$i=1;
while(file_exists($path.$filename.$extension)){
$filename=$file['filename']."teste_($i)";
$i++;}
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(!is_dir($path)){mkdir($path, 0755);} // If dont exist, create folder
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$filename.$extension);
}
}
}
}
echo json_encode (json_decode ("{}"));
?>
提前谢谢你,
答案 0 :(得分:5)
在新创建的目录中尝试使用以下代码来上传文件。
<?php
define("SITE_NAME","project_name/"); //constant for project name
define("SITE_PATH",$_SERVER['DOCUMENT_ROOT']."/".SITE_NAME); //constant for project base directory
define("IMAGES_URL",SITE_URL."images/"); //constant for image directory
$upload_base_dir=IMAGES_URL;
$upload_time_dir=date('Y')."/".date('m')."/".date('d')."/"; // setup directory name
$upload_dir = $upload_base_dir.$upload_time_dir;
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true); //create directory if not exist
}
$image_name=basename($_FILES['image']['name']);
$image=time().'_'.$image_name;
move_uploaded_file($_FILES['image']['tmp_name'],$upload_dir.$image); // upload file
?>
答案 1 :(得分:2)
if(!is_dir($ path)){mkdir($ path,0755); 将其更改为777并检查是否有帮助 或试试这个
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z (Z)");