/    Sign up×
Community /Pin to ProfileBookmark

Change file name before upload

Our asp.net aspx page uses the following javascript and jquery code to do an immediate resize andupload when the input file element (browse) button is clicked. This is used in a public site and many times from a smartphone. Problem is that an iPhone will not give a unique name to a camera-taken file and names all of them “image.jpg”. This causes an overwrite when someone previously uploads a camera picture. We also save the file names as an array in a Textbox named txtFilesUploaded. The file names are saved in a text file and uploaded after all photos are uploaded. Can anyone tell me where the file name can be changed so that the uploaded resized file name is unique? I was thinking of adding a date and time (hhmmss) string (e.g. 20211203144355) to the file name so it is unique.

“`
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]);

var sdate = new Date().toLocaleTimeString(“en-US”).replace(/:/g, ”);
sdate = Left(sdate, sdate.length – 3) + new Date().getSeconds();

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 + ‘~’;
}
“`

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@NogDogDec 04.2021 — I suck at JavaScript, but wondering if it might be easier to handle the renaming in the server-side script that receives the request? That way you don't have to worry about how client apps/browsers handle things.
Copy linkTweet thisAlerts:
@SempervivumDec 04.2021 — Yes, doing this server side would be one way to go. The javascript way:
``<i>
</i> const timeStr = (new Date()).toISOString();
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl,
fileName: file.name.replace(/(.+)(.[^.]+)$/, '$1-' + timeStr + '$2')
});<i>
</i>
`</CODE>

BTW: Single backticks (probably created by the button <C>
&lt;/&gt;</C>) won't work reliably when posting code. You better use code tags: <C>your code here` or triple backticks. I edited your posting accordingly.
Copy linkTweet thisAlerts:
@dlchaseauthorDec 05.2021 — @NogDog#1640154 I am doing it at the client because we need to shrink the image and upload it in the background. We were getting too many errors because the users were uploading 5+mb photos. The current upload uses jquery ajax as soon as their image is selected. It works great except for the file name.
Copy linkTweet thisAlerts:
@dlchaseauthorDec 05.2021 — @Sempervivum#1640159 Can you explain the replace?
Copy linkTweet thisAlerts:
@SempervivumDec 05.2021 — The replace uses a regular expression in order to insert date and time left of the rightmost dot. The text inside the braces is a group and can be referenced in the replacement by $1, $2 or more if there were more groups.

This is a test tool fine for learning and testing regexes:

https://regex101.com

Try to insert the regex and some text or filename. Detailed explanations will be shown at the right.
Copy linkTweet thisAlerts:
@dlchaseauthorDec 05.2021 — @Sempervivum#1640210 Thanks, I will give it a try.
Copy linkTweet thisAlerts:
@dlchaseauthorDec 06.2021 — @Sempervivum#1640159 BTW the Date().toISOString() creates a string with colon and period in it which is bad for a file name.
Copy linkTweet thisAlerts:
@SempervivumDec 06.2021 — I see, wasn't aware of this. Try to remove both or replace it with, e. g. underline:

` const timeStr = (new Date()).toISOString().replace(/:/g, '').replace('.', '_');`
×

Success!

Help @dlchase spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...