locked
File rename before save RRS feed

  • Question

  • User1510859543 posted

    We use the code below to grab a photo image from a camera or local file, upload it and save it to a virtual drive on a webserver. Each file we resize and save usually has a different name. However, it appears if the image is taken from a camera then the name of the file could be the same for each photo. This causes a problem because the image saved overlays the image file name previously saved.  We place the file names in an array separated by a ~ and use this array to grab each image from the webserver. The array of file names is kept in a textbox named txtFilesUploaded. I will also note that the code uses event.fileName for the file name and would like to add date and time string to it before it is saved if found in the array. An example array is 'photo1.jpg~photo2.jpg~photox.jpg'  So if we have a new photo with event.fileName of photo1.jpg I would like to save it something like photo120210423130000.jpg

        window.uploadPhotos = function(url){
            // Read in file
            var file = event.target.files[0];
    
            // Ensure it's an image
            if(file.type.match(/image.*/)) {
                var reader = new FileReader();
                reader.onload = function (readerEvent) {
                    var image = new Image();
                    image.onload = function (imageEvent) {
                        // Resize the image
                        // TODO : pull max size from a site config
                        var canvas = document.getElementById('thecanvas');
                        var max_size = 600;
                        var width = image.width;
                        var height = image.height;
                        if (width > height) {
                            if (width > max_size) {
                                height *= max_size / width;
                                width = max_size;
                            }
                        } else {
                            if (height > max_size) {
                                width *= max_size / height;
                                height = max_size;
                            }
                        }
                        canvas.width = width;
                        canvas.height = height;
                        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                        var dataUrl = canvas.toDataURL('image/jpeg').replace("image/jpeg", "image/octet-stream");
                        
                        var resizedImage = dataURLToBlob(dataUrl);
                        $.event.trigger({
                            type: "imageResized",
                            blob: resizedImage,
                            url: dataUrl,
                            fileName: file.name
                        });
                    }
                    image.src = readerEvent.target.result;
                }
                reader.readAsDataURL(file);
            }
        };
    
    
        /* Utility function to convert a canvas to a BLOB */
            var dataURLToBlob = function (dataURL) {
            var BASE64_MARKER = ';base64,';
            if (dataURL.indexOf(BASE64_MARKER) == -1) {
                var parts = dataURL.split(',');
                var contentType = parts[0].split(':')[1];
                var raw = parts[1];
    
                return new Blob([raw], {type: contentType});
            }
    
            var parts = dataURL.split(BASE64_MARKER);
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
    
            var uInt8Array = new Uint8Array(rawLength);
    
            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
    
            return new Blob([uInt8Array], {type: contentType});
        }
        /* End Utility function to convert a canvas to a BLOB      */
    
    
        /* Handle image resized events */
            $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                $.ajax({
                    url: 'uploadPhoto.aspx/uploadPhoto',
                    data: JSON.stringify({
                        "imageData": event.url,        // this is image data
                        "fileName": event.fileName
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    success: function (data) {
                        addFileName(event.fileName);
                        //change source of image to new one uploaded
                        var x = 'uploads/' + event.fileName;
                        switch(vupnum) {
                          case 1:
                            $("#Image1").attr("src", x);
                            break;
                          case 2:
                            $("#Image2").attr("src", x);
                            break;
                          case 3:
                            $("#Image3").attr("src", x);
                            break;
                          case 4:
                            $("#Image4").attr("src", x);
                            break;
                          case 5:
                            $("#Image5").attr("src", x);
                            break;
                          case 6:
                            $("#Image6").attr("src", x);
                            break;
                          default:
                            vupnum = vupnum + 0;
                        }
    
                    },
                    error: function (req, status, error) {
                        alert('Sorry...upload failed');
                        var lbl = document.getElementById('LblError');
                        lbl.innerHTML = req.responseText;
    
                    }
                });
            }
            });
    
            function addFileName(sname) {
                var vtxt = document.getElementById('txtFilesUploaded');
                vtxt.value += sname + '~';
            }

    Friday, April 23, 2021 9:34 PM

Answers

  • User1535942433 posted

    Hi dlchase,

    Do you have solved your problems now?You could use this way to get datetime in javascript.

    var today = new Date();
    var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var dateTime = date+' '+time;

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 30, 2021 3:01 AM

All replies

  • User1535942433 posted

    Hi dlchase,

    $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                $.ajax({
                    url: 'uploadPhoto.aspx/uploadPhoto',
                    data: JSON.stringify({
                        "imageData": event.url,        // this is image data
                        "fileName": event.fileName
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    success: function (data) {
                        addFileName(event.fileName);
                        //change source of image to new one uploaded
                        var x = 'uploads/' + event.fileName;
                        switch(vupnum) {
                          case 1:
                            $("#Image1").attr("src", x);
                            break;
                          case 2:
                            $("#Image2").attr("src", x);
                            break;
                          case 3:
                            $("#Image3").attr("src", x);
                            break;
                          case 4:
                            $("#Image4").attr("src", x);
                            break;
                          case 5:
                            $("#Image5").attr("src", x);
                            break;
                          case 6:
                            $("#Image6").attr("src", x);
                            break;
                          default:
                            vupnum = vupnum + 0;
                        }
    
                    },
                    error: function (req, status, error) {
                        alert('Sorry...upload failed');
                        var lbl = document.getElementById('LblError');
                        lbl.innerHTML = req.responseText;
    
                    }
                });
            }
            });

    What's "vupnum" ? 

    If you want to add datetime of filename,you could do like this:

    var x = 'uploads/' + event.fileName + DateTime.Now();

    Best regards,

    Yijing Sun

    Monday, April 26, 2021 6:06 AM
  • User1510859543 posted

    I think that is too late to rename the file as it has already been uploaded. So if the file is named image.jpg when ajax uploads it then adding datetime after the ajax upload will not work for this situation. The array stored in textbox txtFilesUploaded would hold a different filename than the one actually uploaded.  Also, the DateTime.Now() is asp.net code I think, not js code.

    Also, I have to consider that filename needs to be split between name and extension so that only the file name is added to and not the extension (.jpg, .jpeg, .gif, etc.)

    Monday, April 26, 2021 1:59 PM
  • User1535942433 posted

    Hi dlchase,

    Do you have solved your problems now?You could use this way to get datetime in javascript.

    var today = new Date();
    var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var dateTime = date+' '+time;

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 30, 2021 3:01 AM