locked
How to upload multi images using this code? RRS feed

  • Question

  • User-2071692902 posted

    Hi all,

    I'm using this code to send one image each time to div.

    This is the whole code

    <div class="conDiv"  id="conDivID"></div>
              
              <div class=" myInputtextDiv">
                <input style="color:black;" type="text" id="myInput" maxlength="10000">
                <input type="text" id="baseimage" onkeyup=" sendImage()"  hidden  >
                </br>
    <script type="text/javascript">
          function sendImage(){
              alert ("sent")
          }
    
    </script>
    <input id="myBtn" type="button" onclick="sendFunction();" value=" Send">
            <input id="fileInput" type="file" style="display: none;" />
            <input type="button" value="Choose Image!"onclick="document.getElementById                ('fileInput').click();" />
    
            </div>
                 <div class=" chooseBottun">
            </div>
               <br>
    
       <script>
           function sendFunction() {
               var d = new Date()
               var h12 = d.getHours();
               var h24 = d.getHours();
               var m = d.getMinutes();
               var s = d.getSeconds();
               if (s < 10) {
                   s = "0" + s
               }
               if (m < 10) {
                   m = "0" + m
               }
               if (h12 > 12) {
                   h12 = h12 - 12
               }
               if (h12 == 00) {
                       h12  = 12
                   }
    
               var timeStamp = h12 + ":" + m + ":" + s + " ";
               if (h24 > 11) {
                   timeStamp += "PM";
               } else {
                   timeStamp += "AM";
               }
    
              
              if (regex.test(userName)& imagesrc.value !="") {
    $('#conDivID').append("<span style='color: red'>" + userName + ': </span>');
    $('#conDivID').append( embedUrls(userinput));
    $('#conDivID').append('</br>');
    $('#conDivID').append(img);
    $('#conDivID').append('</br>');
    $('#conDivID').append("<span class='timeSpan'>" + timeStamp + '</span>');
    $('#conDivID').append('</br>');
                   
                   document.getElementById('baseimage').value = "";
                   document.getElementById('myInput').value = "";
                   document.getElementById("myInput").focus();
                   }else {
    
                   alert("Please Enter Your Username To Start Chat,Only English Letters And Numbers Allowed Without Spaces Between Them In The Username Field.");
                   document.getElementById("myUserName").value = "";
                   document.getElementById("myUserName").focus();
    
               }
               //To use scrolls on the conDivID.
               document.getElementById("conDivID").scrollTop =
               document.getElementById("conDivID").scrollHeight;
           }
    </script> 
        </form>
        <br>
       
    <script>
    // To display image after browsing for it
        document.getElementById("fileInput").onchange = function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#fileInput').attr('src', e.target.result);
                $('#baseimage').val(e.target.result);
                sendFunction();
            };
            reader.readAsDataURL(this.files[0]);
            
        }
     </script>

    How to upload multi images using this code?

    Thank you your valuable time

    Sunday, December 2, 2018 1:44 PM

All replies

  • User-893317190 posted

    Hi Omanxp45-1,

    You could use formdata to upload your file and use a Generic Handler to save your uploaded file.

    Below is my code.

     <div class="conDiv" id="conDivID"></div>
    
        <div class="myInputtextDiv">
            <input style="color:black;" type="text" id="myInput" maxlength="10000">
            <input type="text" id="baseimage" onkeyup=" sendImage()" hidden>
            <img id="img"  />
            </br>
            <script type="text/javascript">
          function sendImage(){
              alert ("sent")
          }
    
            </script>
            <input id="myBtn" type="button" onclick="sendFunction();" value=" Send">
            <input id="fileInput" type="file" style="display: none;" />
            <input type="button" value="Choose Image!" onclick="document.getElementById                ('fileInput').click();" />
    
        </div>
        <div class=" chooseBottun">
        </div>
        <br>
      
        <script>
           function sendFunction(img) {
              
             // to simplify , I remove the other code
    // append the newly created img to let use preview their image. $('#conDivID').append(img); } </script> </form> <br> <script> // To display image after browsing for it document.getElementById("fileInput").onchange = function () { var reader = new FileReader(); var file = this.files[0]; reader.readAsDataURL(file); reader.onload = function (e) { $('#fileInput').attr('src', e.target.result); $('#baseimage').val(e.target.result);
    // create an image var img = $("<img id='img' />").attr("src", e.target.result) sendFunction(img); }; var xhr = new XMLHttpRequest() // create formdata var formData = new FormData() // add the file to the formdata formData.append('file', file) //send the file to server xhr.open('POST', '/Services/res1.ashx', true) xhr.send(formData) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { // doSomeThing(this) } else { // error(this) } } } } </script>

    code behind.

     public void ProcessRequest(HttpContext context)
            {
               
                context.Response.ContentType = "text/plain";
                context.Response.Write(context.Server.MapPath(context.Request.FilePath));
                HttpPostedFile file = context.Request.Files["file"];
                file.SaveAs(context.Request.MapPath("/upload/" + file.FileName));  //save the file.
                context.Response.Write("ok");
            }

    The result. The left is the html, the right is the uploaded files.

    Best regards,

    Ackerly Xu

    Monday, December 3, 2018 2:56 AM
  • User-2071692902 posted

    Hi

    Here the new code after that I try it but nothing happened

     <form>
      <div class=" UsernameLabelDiv">
     <input style="width: 300px" type="text"  placeholder="Username" id="myUserName"maxlength="10"onkeyup="saveValue(this)" onkeypress="return AvoidSpace(event)">
    </div>
    <div class="conDiv"  id="conDivID"></div>
              
              <div class=" myInputtextDiv">
                <input style="color:black;" type="text" id="myInput" maxlength="10000">
                <input type="text" id="baseimage" onkeyup=" sendImage()"  hidden  >
                </br>
    
    <input id="myBtn" type="button" onclick="sendFunction();" value=" Send">
            <input id="fileInput" type="file" style="display: none;" />
            <input type="button" value="Choose Image!"onclick="document.getElementById                ('fileInput').click();" />
    
            </div>
                 <div class=" chooseBottun">
            </div>
               <br>
    
       <script>
           function sendFunction() {
               var d = new Date()
               var h12 = d.getHours();
               var h24 = d.getHours();
               var m = d.getMinutes();
               var s = d.getSeconds();
               if (s < 10) {
                   s = "0" + s
               }
               if (m < 10) {
                   m = "0" + m
               }
               if (h12 > 12) {
                   h12 = h12 - 12
               }
               if (h12 == 00) {
                       h12  = 12
                   }
    
               var timeStamp = h12 + ":" + m + ":" + s + " ";
               if (h24 > 11) {
                   timeStamp += "PM";
               } else {
                   timeStamp += "AM";
               }
    
               var userName = document.getElementById("myUserName").value;
               var userinput = document.getElementById("myInput").value;
               var imagesrc = document.getElementById("baseimage");
               var img = $('<img class="img" width=" =100px;" height=" 100px">')
                           .attr('src', imagesrc.value);
              
    
    $('#conDivID').append("<span style='color: red'>" + userName + ': </span>');
    $('#conDivID').append( embedUrls(userinput));
    $('#conDivID').append('</br>');
    $('#conDivID').append(img);
    $('#conDivID').append('</br>');
    $('#conDivID').append("<span class='timeSpan'>" + timeStamp + '</span>');
    $('#conDivID').append('</br>');
                   
                
                   
           }
    </script> 
        </form>
     <script>
    // To display image after browsing for it
        document.getElementById("fileInput").onchange = function () {
            var reader = new FileReader();
            var file = this.files[0];
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                $('#fileInput').attr('src', e.target.result);
                $('#baseimage').val(e.target.result);
                     // create an image
                var img = $("<img id='img'  />").attr("src", e.target.result)
          
                sendFunction(img);
    
            };
    
            var xhr = new XMLHttpRequest()
    
            // create formdata
            var formData = new FormData()
    
            // add the file to the formdata
            formData.append('file', file)
             //send the file to server
            xhr.open('POST', '/Services/res1.ashx', true)
            xhr.send(formData)
    
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        // doSomeThing(this)
                    } else {
                        // error(this)
                    }
                }
            }
    
           
    
            }
    
           
        </script>

    Monday, December 3, 2018 10:57 PM
  • User-893317190 posted

    Hi Omanxp45-1,

    You could change your code as follows,

    <script>
           function sendFunction(newImage) {//please set a argument in your function,or it won't receive the value you pass
               var d = new Date()
               var h12 = d.getHours();
               var h24 = d.getHours();
               var m = d.getMinutes();
               var s = d.getSeconds();
               if (s < 10) {
                   s = "0" + s
               }
               if (m < 10) {
                   m = "0" + m
               }
               if (h12 > 12) {
                   h12 = h12 - 12
               }
               if (h12 == 00) {
                       h12  = 12
                   }
    
               var timeStamp = h12 + ":" + m + ":" + s + " ";
               if (h24 > 11) {
                   timeStamp += "PM";
               } else {
                   timeStamp += "AM";
               }
    
               var userName = document.getElementById("myUserName").value;
               var userinput = document.getElementById("myInput").value;
               var imagesrc = document.getElementById("baseimage");
               var img = $('<img class="img" width=" =100px;" height=" 100px">')
                           .attr('src', imagesrc.value);
              
    
    $('#conDivID').append("<span style='color: red'>" + userName + ': </span>');
    $('#conDivID').append( embedUrls(userinput));
    $('#conDivID').append('</br>');
    $('#conDivID').append(newImage);
    $('#conDivID').append('</br>');
    $('#conDivID').append("<span class='timeSpan'>" + timeStamp + '</span>');
    $('#conDivID').append('</br>');
                   
                
                   
           }
    </script> 
        </form>
     <script>
    // To display image after browsing for it
        document.getElementById("fileInput").onchange = function () {
            var reader = new FileReader();
            var file = this.files[0];
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                $('#fileInput').attr('src', e.target.result);
                $('#baseimage').val(e.target.result);
                     // create an image
                var img = $("<img />").attr("src", e.target.result)
          
                sendFunction(img);
    
            };
    
            var xhr = new XMLHttpRequest()
    
            // create formdata
            var formData = new FormData()
    
            // add the file to the formdata
            formData.append('file', file)
             //send the file to server
            xhr.open('POST', '/Services/res1.ashx', true)
            xhr.send(formData)
    
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        // doSomeThing(this)
                    } else {
                        // error(this)
                    }
                }
            }
    
           
    
            }
    
           
        </script>

    You write the code  xhr.open('POST', '/Services/res1.ashx', true),do you have a ashx named res1 and in the folder Services?

    '/Services/res1.ashx' is just an address, if you have no ashx, it won't work. Please write your own ashx's address to deal with the ajax request.

    Best regards,

    Ackerly Xu

    Tuesday, December 4, 2018 1:29 AM
  • User-2071692902 posted

    I haven't put my site on the net yet 

    Tuesday, December 4, 2018 6:24 AM
  • User-893317190 posted

    Hi Omanxp45-1,

    I don't understand what you mean clearly.If you need to upload muti images, you need an ashx to deal with the ajax request (which contains the data of your image).

    You don't need  publish you website.

    It is just an ashx in you project, just right click your project , click add new item , enter Generic Handler in the search bar, it will occur.

    https://stackoverflow.com/questions/8466941/upload-file-using-jquery-and-handlerashx

    If you only want to show your image using base64, you could remove the code below.

    What I do is not only showing the user images but also uploading the image to the server and save it in a folder  in the server.

     var xhr = new XMLHttpRequest()
    
            // create formdata
            var formData = new FormData()
    
            // add the file to the formdata
            formData.append('file', file)
             //send the file to server
            xhr.open('POST', '/Services/res1.ashx', true)
            xhr.send(formData)
    
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        // doSomeThing(this)
                    } else {
                        // error(this)
                    }
                }
            }
    
           
    

    Best regards,

    Ackerly Xu

    Tuesday, December 4, 2018 6:39 AM
  • User-2071692902 posted

    No , I just want to make user able to send more than one image to the chat conversation"conDivID" without saving them.

    here the code that I put it in my project as you give it to me 

        <body>
         
                     <div class="conDiv" id="conDivID"></div>
     
        <div class="myInputtextDiv">
            <input style="color:black;" type="text" id="myInput" maxlength="10000">
            <input type="text" id="baseimage" onkeyup=" sendImage()" hidden>
            <img id="img"  />
            </br>
            <script type="text/javascript">
          function sendImage(){
              alert ("sent")
          }
     
            </script>
            <input id="myBtn" type="button" onclick="sendFunction();" value=" Send">
            <input id="fileInput" type="file" style="display: none;" />
            <input type="button" value="Choose Image!" onclick="document.getElementById                ('fileInput').click();" />
     
        </div>
        <div class=" chooseBottun">
        </div>
        <br>
      
       <script>
           function sendFunction(newImage) {//please set a argument in your function,or it won't receive the value you pass
               var d = new Date()
               var h12 = d.getHours();
               var h24 = d.getHours();
               var m = d.getMinutes();
               var s = d.getSeconds();
               if (s < 10) {
                   s = "0" + s
               }
               if (m < 10) {
                   m = "0" + m
               }
               if (h12 > 12) {
                   h12 = h12 - 12
               }
               if (h12 == 00) {
                       h12  = 12
                   }
     
               var timeStamp = h12 + ":" + m + ":" + s + " ";
               if (h24 > 11) {
                   timeStamp += "PM";
               } else {
                   timeStamp += "AM";
               }
     
               var userName = document.getElementById("myUserName").value;
               var userinput = document.getElementById("myInput").value;
               var imagesrc = document.getElementById("baseimage");
               var img = $('<img class="img" width=" =100px;" height=" 100px">')
                           .attr('src', imagesrc.value);
              
    $('#conDivID').append("<span style='color: red'>" + userName + ': </span>');
    $('#conDivID').append( embedUrls(userinput));
    $('#conDivID').append('</br>');
    $('#conDivID').append(newImage);
    $('#conDivID').append('</br>');
    $('#conDivID').append("<span class='timeSpan'>" + timeStamp + '</span>');
    $('#conDivID').append('</br>');
                   
                
                   
           }
    </script> 
        </form>
     <script>
    // To display image after browsing for it
        document.getElementById("fileInput").onchange = function () {
            var reader = new FileReader();
            var file = this.files[0];
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                $('#fileInput').attr('src', e.target.result);
                $('#baseimage').val(e.target.result);
                     // create an image
                var img = $("<img />").attr("src", e.target.result)
          
                sendFunction(img);
     
            };
     
    </script>
        </body>
    

    But it still not working.Where are errors?
    Tuesday, December 4, 2018 3:07 PM
  • User-893317190 posted

    Hi Omanxp45-1,

    I have highlighted my changes , you could refer to it.

    <body>
        <form>
            <div class="conDiv" id="conDivID"></div>
    
            <div class="myInputtextDiv">
                <input style="color:black;" type="text" id="myInput" maxlength="10000">
                <input type="text" id="baseimage" onkeyup=" sendImage()" hidden>
                <img id="img" />
                </br>
                <script type="text/javascript">
                    function sendImage() {
                        alert("sent")
                    }
    
                </script>
              
        
                <input id="myBtn" type="button" onclick="sendFunction();" value=" Send">
                <input id="fileInput" type="file" style="display: none;" />
                <input type="button" value="Choose Image!" onclick="document.getElementById('fileInput').click();" />
    
            </div>
            <div class=" chooseBottun">
            </div>
            <br>
    
            <script>
                function sendFunction(newImage) {//please set a argument in your function,or it won't receive the value you pass
                    var d = new Date()
                    var h12 = d.getHours();
                    var h24 = d.getHours();
                    var m = d.getMinutes();
                    var s = d.getSeconds();
                    if (s < 10) {
                        s = "0" + s
                    }
                    if (m < 10) {
                        m = "0" + m
                    }
                    if (h12 > 12) {
                        h12 = h12 - 12
                    }
                    if (h12 == 00) {
                        h12 = 12
                    }
    
                    var timeStamp = h12 + ":" + m + ":" + s + " ";
                    if (h24 > 11) {
                        timeStamp += "PM";
                    } else {
                        timeStamp += "AM";
                    }
    
                   // var userName = document.getElementById("myUserName").value;  //I don't have the element,please ensure in your code there is an 
                    var userinput = document.getElementById("myInput").value;         //element with the id "myUserName"
                    var imagesrc = document.getElementById("baseimage");
                    var img = $('<img class="img" width=" =100px;" height=" 100px">')
                        .attr('src', imagesrc.value);
    
                    $('#conDivID').append("<span style='color: red'>" + userName + ': </span>');
                    //$('#conDivID').append(embedUrls(userinput));   //I don't have the function embedUrls, please ensure you have a function named embedUrls
                    $('#conDivID').append('</br>');
                    $('#conDivID').append(newImage);
                    $('#conDivID').append('</br>');
                    $('#conDivID').append("<span class='timeSpan'>" + timeStamp + '</span>');
                    $('#conDivID').append('</br>');
    
    
    
                }
            </script>
        </form>
        <script>
            // To display image after browsing for it
            document.getElementById("fileInput").onchange = function () {
                var reader = new FileReader();
                var file = this.files[0];
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    $('#fileInput').attr('src', e.target.result);
                    $('#baseimage').val(e.target.result);
                    // create an image
                    var img = $("<img />").attr("src", e.target.result)
    
                    sendFunction(img);
    
                };
            } 
             //please don't forget the last semicolon                  
        </script>
    </body>
    </html>

    Best regards,

    Ackerly Xu

    Wednesday, December 5, 2018 1:16 AM
  • User-2071692902 posted

    Hi Ackerly Xu,

    Sorry but the code still not working for multi images. It is only accept one image each time. 

    Wednesday, December 5, 2018 6:38 AM
  • User-893317190 posted

    Hi Omanxp45-1,

    Your js's design is when the user chooses an image, add an image,so the code deals with one image each time and show the selected image using base64.

    I don't understand why you want to show muti images each time when the user only choose one image each time.

    You could let use choose muti images ,please use ,and consider using it to design your js, onchange event fires each time the user selects one image

     <input type="file" id="myfileinput" multiple>

    Please refer to https://developer.mozilla.org/en-US/docs/Web/API/FileList

    Or you could consider save the user's selected image in an array and show all the image saved in the array at last.

    Best regards,

    Ackerly Xu

    Wednesday, December 5, 2018 7:24 AM