Issue with uploading image using this.form.submit();

Asked
Active3 hr before
Viewed126 times

9 Answers

uploadingusingissueimage
90%

Meta Stack Overflow , Stack Overflow Public questions & answers , Stack Overflow help chat ,I am using this.form.submit(); in order to upload an image straight after it is sellected and also pass some other info along.

It really was something stupid that I didn't see as I mentioned in my comment above... If you check closely the if(file_exists) you can see that the stmt is inside it and well... there wasn't an else to upload so if an image was unique nothing happened so I just coppied the move_uploaded_file and the rest and added an else{ and that fixed the issue.

if (isset ($_POST['image'])) {
    $cust_id = $_POST['id'];
    $images = $_FILES['image']['name'];
    $tmp_dir = $_FILES['image']['tmp_name'];
    $imageSize = $_FILES['image']['size'];

if (!is_dir('img/logotipa/'.$cust_id)){
    mkdir('img/logotipa/'.$cust_id, 0777, true);
}

$upload_dir = 'img/logo/'.$cust_id.'/';
$imgExt = strtolower(pathinfo($images,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$up_image = $images;

if (file_exists($upload_dir.$images)){
    $counter = 0;
    
    while (file_exists($upload_dir.$up_image)){
        $up_image = $counter.'_'.$images;
        $counter++;            
    }

    move_uploaded_file($tmp_dir, $upload_dir.$images);
    $stmt = $conn->prepare('INSERT INTO logos(customer_id, logo) VALUES (:ucid, :upic)');
    $stmt->bindParam(':ucid', $cust_id);
    $stmt->bindParam(':upic',  $up_image);

    if ($stmt->execute()){
        echo '<script>window.location.href = "customer_logo.php";</script>';
    
    }
}else{
move_uploaded_file($tmp_dir, $upload_dir.$images);
        $stmt = $conn->prepare('INSERT INTO logos(customer_id, logo) VALUES (:ucid, :upic)');
        $stmt->bindP

aram(':ucid', $cust_id);
    $stmt->bindParam(':upic',  $up_image);

    if ($stmt->execute()){
        echo '<script>window.location.href = "customer_logo.php";</script>';
    
    }
}
88%

Uploading images or files is a major function of any app. It is an essential requirement for creating a truly full-stack app. For example, Facebook, Instagram, and Snapchat all have the functionality to upload images and videos. ,That's pretty much it. You have successfully created and added a custom file upload component.,Now, add state in the component to store the name and the file data.,File uploading is an essential part of any web app. You can use other third-party libraries to create custom file upload inputs, but you should have a fair idea of how they are implemented under the hood.

1import React from "react";
2
3const App = () => {
4  return (
5    <div className="App">
6      <form>
7        <input type="text" />
8
9        <input type="file" />
10      </form>
11    </div>
12  );
13};
load more v
72%

A common problem with file input in forms is that form data gets sent but only the name of the file is included. The reason is typically that the form element does not contain the attributes mentioned above.,The following example demonstrates how your browser treats a file input element where we suggest presentational properties both in HTML and in CSS:,Although most browsers have supported file input for a long time, the quality of implementations is poor. Therefore users easily get confused with file input.,The file is submitted as such, without code conversions. A plain text file is submitted without information about character encoding, so the recipient needs to guess the encoding or infer it somehow.

The HTML markup is:

<form action="http://jkorpela.fi/cgi-bin/echo.cgi" enctype="multipart/form-data" method="post">
   <p>
      Type some text (if you like):<br>
      <input type="text" name="textline" size="30">
   </p>
   <p>
      Please specify a file, or a set of files:<br>
      <input type="file" name="datafile" size="40">
   </p>
   <div>
      <input type="submit" value="Send">
   </div>
</form>
load more v
65%

Unique file type specifiers,The string image/* meaning "any image file".,The string video/* meaning "any video file".,The string audio/* meaning "any audio file".

<input type="file" id="docpicker" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
load more v
75%

works, but the upload change the oietaion... original portrait to landscape...How can i fix this?,Mubashar Ahmed9 April 2020 at 02:24sir the image is disappear after the refresh how to fix it ReplyDeleteRepliesReply,It works. I need to change this script to fit Codeigniter. Can you help?,Works perfectly. Thanks But is there a way i can send like a text in addition to the image to php?


<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Upload File without using Form Submit in Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:700px;">
   <h2 align="center">Upload File without using Form Submit in Ajax PHP</h2>
   <br />
   <label>Select Image</label>
   <input type="file" name="file" id="file" />
   <br />
   <span id="uploaded_image"></span>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $(document).on('change', '#file', function(){
  var name = document.getElementById("file").files[0].name;
  var form_data = new FormData();
  var ext = name.split('.').pop().toLowerCase();
  if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
  {
   alert("Invalid Image File");
  }
  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById("file").files[0]);
  var f = document.getElementById("file").files[0];
  var fsize = f.size||f.fileSize;
  if(fsize > 2000000)
  {
   alert("Image File Size is very big");
  }
  else
  {
   form_data.append("file", document.getElementById('file').files[0]);
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){
     $('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
    },   
    success:function(data)
    {
     $('#uploaded_image').html(data);
    }
   });
  }
 });
});
</script>

load more v
40%

Configure and Connect MySQL Database With PHP,Using jQuery & AJAX for File Upload Form,The Process of File Uploading in PHP,In this tutorial, I demonstrated image and file upload in PHP using AJAX and jQuery. Here is a functional demo of the application where you could see the app in action. In my next tutorial, I will demonstrate how you could upload and store a file into the database using PDO.

Another important attribute is enctype which should be set to multipart/form-data. Last but not least, the file <input> type attribute should be set to file.

Create a file index.php in your PHP project and type in the following code.

<!doctype html>
<html>

<head lang="en">
   <meta charset="utf-8">
   <title>Ajax File Upload with jQuery and PHP</title>
   <link rel="stylesheet" href="style.css" type="text/css" />
   <script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
   <script type="text/javascript" src="js/script.js"></script>

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<body>
   <div class="container">
      <div class="row">

         <div class="col-md-8">

            <h1><a href="#" target="_blank"><img src="logo.png" width="80px" />Ajax File Uploading with Database MySql</a></h1>
            <hr>

            <form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
               <div class="form-group">
                  <label for="name">NAME</label>
                  <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
               </div>
               <div class="form-group">
                  <label for="email">EMAIL</label>
                  <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
               </div>

               <input id="uploadImage" type="file" accept="image/*" name="image" />
               <div id="preview"><img src="filed.png" /></div><br>
               <input class="btn btn-success" type="submit" value="Upload">
            </form>

            <div id="err"></div>
            <hr>
            <p><a href="https://www.cloudways.com" target="_blank">www.Cloudways.com</a></p>
         </div>
      </div>
   </div>
</body>

</html>

Since I will use jQuery & AJAX for submitting data and uploading the files, I will start by including the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
$(document).ready(function(e) {
   $("#form").on('submit', (function(e) {
      e.preventDefault();
      $.ajax({
         url: "ajaxupload.php",
         type: "POST",
         data: new FormData(this),
         contentType: false,
         cache: false,
         processData: false,
         beforeSend: function() {
            //$("#preview").fadeOut();
            $("#err").fadeOut();
         },
         success: function(data) {
            if (data == 'invalid') {
               // invalid file format.
               $("#err").html("Invalid File !").fadeIn();
            } else {
               // view uploaded file.
               $("#preview").html(data).fadeIn();
               $("#form")[0].reset();
            }
         },
         error: function(e) {
            $("#err").html(e).fadeIn();
         }
      });
   }));
});

The next step is setting up and configuring the MySQL database. Go to the Cloudways Database Manager and create a table named ‘uploading’. The fields of this table are name, email, file_name. Alternatively, you could use the following SQL query:

CREATE TABLE `uploading`(

   `id`
   int(11) NOT NULL AUTO_INCREMENT,

   `name`
   varchar(100) COLLATE utf8_unicode_ci NOT NULL,

   `email`
   varchar(100) COLLATE utf8_unicode_ci NOT NULL,

   `file_name`
   varchar(100) COLLATE utf8_unicode_ci NOT NULL,

   PRIMARY KEY(`id`)

) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;

Next, create db.php to connect the database with the PHP application. Paste the following code snippet in the file:

< ? php

//DB details

$dbHost = 'localhost';

$dbUsername = 'fkmc';

$dbPassword = '';

$dbName = 'fkc';

//Create connection and select DB

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db - > connect_error) {

   die("Unable to connect database: ".$db - > connect_error);

}

In this case, $_FILES[“image”] is the index name.more information about the file is stored in the following indexes.

< ? php
$img = $_FILES["image"]["name"] stores the original filename from the client
$tmp = $_FILES["image"]["tmp_name"] stores the name of the designated temporary file
$errorimg = $_FILES["image"][“error”] stores any error code resulting from the transfer ?
   >

Let’s create the PHP script to deal with the functionality of file uploading. Create ajaxupload.php and type the following code in it.

<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions
$path = 'uploads/'; // upload directory

if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['image'])
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];

// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

// can upload same image using rand function
$final_image = rand(1000,1000000).$img;

// check's valid format
if(in_array($ext, $valid_extensions)) 
{ 
$path = $path.strtolower($final_image); 

if(move_uploaded_file($tmp,$path)) 
{
echo "<img src='$path' />";
$name = $_POST['name'];
$email = $_POST['email'];

//include database configuration file
include_once 'db.php';

//insert form data in the database
$insert = $db->query("INSERT uploading (name,email,file_name) VALUES ('".$name."','".$email."','".$path."')");

//echo $insert?'ok':'err';
}
} 
else 
{
echo 'invalid';
}
}
?>

To check the error in the uploaded file, type in the following code, If the error is greater than zero then there must be an error in the process.

if($errorimg > 0){

   die('<div class="alert alert-danger" role="alert"> An error occurred while uploading the file </div>');

}

The file size is measured in bytes. So, if the file size is set at 500kb, then the file size should be less than 500000.

if($myFile['size'] > 500000){

   die('<div class="alert alert-danger" role="alert"> File is too big </div>');

}

Add the following code in the <form> tag where you want your reCAPTCHA to be placed:

require_once('recaptchalib.php');
$publickey = "your_public_key"; //you got this from the signup page
echo recaptcha_get_html($publickey);
< ? php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if (!$resp - > is_valid) {
   die("The reCAPTCHA wasn't entered correctly. Go back and try it again.".
      "(reCAPTCHA said: ".$resp - > error.
      ")");
} else {
   // Your code here to handle a successful verification
} ?
>
load more v
22%

I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax. here is my code:,Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly. The solution is:,This code should do the trick. Sorry was a long time ago and I thought that IE9 also could upload using XHR (It should, but this is the Iframe option).,This blog post aptly describes the method of saving canvases onto the server with AJAX queries, I guess this should be fitting for you.

html:

<div id="uploadPic" onclick="getFile()">
   Select a photo to upload
</div>
<form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action="">
   <div style='height: 0px;width:0px; overflow:hidden;'>
      <input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()">
   </div>
</form>

javascript:

function getFile() {
   document.getElementById("upfile").click();
}

function sub1() {
   var photo = document.getElementById("upfile");
   var file = photo.files[0];
   data = new FormData();
   data.append('file', file);
   $.ajax({
      url: 'url',
      data: data
      enctype: 'multipart/form-data',
      processData: false, // do not process the data as url encoded params
      contentType: false, // by default jQuery sets this to urlencoded string
      type: 'POST',
      success: function(output) {
         document.getElementById('picTmp').innerHTML = output;;
      }
   });
}

PHP code:

if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "") {
   $fileName = $_FILES["avatar"]["name"];
   $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
   $fileType = $_FILES["avatar"]["type"];
   $fileSize = $_FILES["avatar"]["size"];
   $fileErrorMsg = $_FILES["avatar"]["error"];
   $kaboom = explode(".", $fileName);
   $fileExt = end($kaboom);
   list($width, $height) = getimagesize($fileTmpLoc);
   .......
}
load more v
60%

In the HTML window of WebForm1, replace the form tag with the following:,In the HTML window of WebForm1, add the following code between the opening and the closing <form> tags:,This Button control is used to upload the file that you specified in the Input control.,This Button control is used to upload the file that you specified in the Input control.

In the HTML window of WebForm1, replace the form tag with the following:

<form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">

In the HTML window of WebForm1, add the following code between the opening and the closing <form> tags:

<INPUT id="oFile" type="file" runat="server" NAME="oFile">

In the HTML window of WebForm1, add the following code between the opening and closing <form> tags, after the Input control code:

<asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>

In the HTML window of WebForm1, add the following code between the opening and closing <form> tags, after the Button control code:

<asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
   <asp:Label id="lblUploadResult" Runat="server"></asp:Label>
</asp:Panel>

Add the following code at the top of the Code window:

using System.IO;

Add the following code to the Click event handler for the Upload button:

string strFileName;
string strFilePath;
string strFolder;
strFolder = Server.MapPath("./");
// Retrieve the name of the file that is posted.
strFileName = oFile.PostedFile.FileName;
strFileName = Path.GetFileName(strFileName);
if (oFile.Value != "") {
   // Create the folder if it does not exist.
   if (!Directory.Exists(strFolder)) {
      Directory.CreateDirectory(strFolder);
   }
   // Save the uploaded file to the server.
   strFilePath = strFolder + strFileName;
   if (File.Exists(strFilePath)) {
      lblUploadResult.Text = strFileName + " already exists on the server!";
   } else {
      oFile.PostedFile.SaveAs(strFilePath);
      lblUploadResult.Text = strFileName + " has been successfully uploaded.";
   }
} else {
   lblUploadResult.Text = "Click 'Browse' to select the file to upload.";
}
// Display the result of the upload.
frmConfirmation.Visible = true;

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
   Inherits="Howto.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>

<HEAD>
   <title>WebForm1</title>
   <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
   <meta name="CODE_LANGUAGE" Content="C#">
   <meta name="vs_defaultClientScript" content="JavaScript">
   <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>

<body MS_POSITIONING="GridLayout">
   <form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">
      Image file to upload to the server: <INPUT id="oFile" type="file" runat="server" NAME="oFile">
      <asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
      <asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
         <asp:Label id="lblUploadResult" Runat="server"></asp:Label>
      </asp:Panel>
   </form>
</body>

</HTML>
load more v
48%

But it requires a form submit for uploading the selected file.,If it is not 0 then update the <img > source otherwise alert('file not uploaded') message.,Send the selected file using the FormData object in the AJAX request.,Use FormData object to store the file and pass in the AJAX request to upload it.

Completed Code

<div class="container">
   <form method="post" action="" enctype="multipart/form-data" id="myform">
      <div class='preview'>
         <img src="" id="img" width="100" height="100">
      </div>
      <div>
         <input type="file" id="file" name="file" />
         <input type="button" class="button" value="Upload" id="but_upload">
      </div>
   </form>
</div>
load more v

Other "uploading-using" queries related to "Issue with uploading image using this.form.submit();"