I have a file input in a form that uploads an MP3 file, but I´d like to detect reserved characters to my system in the filename, like ! # or any other.
All codes I´ve found replace these characters, but I just want to detect them to alert the user. I think it will be easy with regular expressions, but I dont know about them.
I´m using JQuery/Javascript.
Edit to improve my problem description:
I´m working in a CodeIgniter application that allows user to upload MP3 files to the server. I use jQuery to manage client side forms. The CI upload class converts spaces in the file name to underscores and everything works. But in testing the application I uploaded an MP3 file with a (!) in the name, and I got troubles with it.
I just want to insert a javascript conditional before the file is uploaded to evaluate if the user´s filename contains a (!) (or any other I´d like to add later) to ask for the file to be renamed if it does.
Consider not blocking any characters at all. It's just a hassle for the user, and on exotic systems with strange path characters, you may end up not letting the user upload anything at all.
Let the user upload the file, and store the file name on the server in URI-Encoded form (in PHP, urlencode() would be the right function to go). This makes the file name compatible with your OS, and allows the user to keep any special characters in it when re-downloading the file.
One way to do this would be to compare the actual value of the input field to one encoded by encodeURIComponent. If they are the same, the filename is safe.
Be aware, though, that the browser may not report any filename at all. My plugin responds to this by returning true if no value is returned. This may, of course, mean that no value has been set.
jQuery plugin:
(function($) {
$.fn.fileNameIsValid = function() {
var val = this[0].value.replace('C:\\fakepath\\', '');
return !val || encodeURIComponent(val) === val;
}
}(jQuery));
You can then call this as so:
if ($('#yourFileInput').fileNameIsValid()) {
// filename validates
}
Related
What I need to do is:
Let user choose txt file from his disc
Get the text from it to let's say a variable
Send it (the variable value) via AJAX
For the first point I want to know if I should use normal input type (like if I would like to send file via POST) <input type="file">
For the second point I need to know how to get the name of the file user selected and then read text from it. Also I'm not good with javascript so I don't really know how long can a string be there (file will have about 15k lines on average)
For the third I need nothing to know if I can have the data stored in a variable or an array.
Thanks in advance.
P.S. I guess javascript is not a fast language, but (depending on the editor) it sometimes opens on my computer the way that I have all the needed data in first 5 or 6 lines. Is it possible to read only first few lines from the file?
It is possible to get what you want using the File API as #dandavis and other commentors have mentioned (and linked), but there are some things to consider about that solution, namely browser support. Bottom line is the File API is currently a working draft of the w3c. And bottom line is even w3c recommended things aren't always fully supported by all browsers.
What solution is "best" for you really boils down to what browser/versions you want to support. If it were my own personal project or for a "modern" site/audience, I would use the File API. But if this is for something that requires maximum browser support (for older browsers), I would not currently recommend using the File API.
So having said all that, here is a suggested solution that does NOT involve using the FIle API.
supply an input type file in a form for the user to specify file. User will have to select the file (javascript cannot do this)
use form.submit() or set the target attribute to submit the form. There is an iframe trick for submitting a form without refreshing the page.
use server-side language of choice to respond with the file info (name, contents, etc.). For example in php you'd access the posted file with $_FILES
then you can use javascript to parse the response. Normally you'd send it as a json encoded response. Then you can do whatever you want with the file info in javascript.
With Chrome and Firefox you can read the contents of a text file like this:
HTML:
<input type="file" id="in-file" />
JavaScript with jQuery:
var fileInput = $('#in-file');
fileInput.change(function(e) {
var reader = new FileReader();
reader.onload = function(e) {
console.log(reader.result);
}
reader.readAsText(fileInput[0].files[0]);
});
IE doesn't support the FileReader object.
I assigned a string to a javascript string object, such like :
var word = "Please input correct verb"
I want this string be in control by resource file in asp.net project. Does it provide the function to replace the string using a ASP.NET syntax to switch languages?
<%$ Resources:Registration, correctverb%>
Thanks.
There are various l18n projects for JavaScript, e.g. http://i18next.com/
If you have ResX files in your ASP project and you want them as JavaScript or JSON files you can convert them here; or via the REST API you could convert a resource file as follows:
$ curl --data-binary #messages.resx \
http://localise.biz/api/convert/resx/messages.json
(example in cURL, which I guess you may not have if you're on Windows)
A common approach for this is creating an HTTP handler that evaluates requests for say files with the extension *.js.axd (or whatever extension you come up with) and then parse the javascript file by replacing defined tokens with the actual localized resource value.
It may be costly only the first time the file is requested but then everything should run smoothly if caching is applied. Here's an example of how to create a handler, parsing the file should be trivial. You could use the same syntax to define localized strings on your file: <% LocalizedResourceName %>
I am trying to use docx.js to generate a Word document but I can't seem to get it to work.
I copied the raw code into the Google Chrome console after amending line 247 to fix a "'textAlign' undefined error"
if (inNode.style && inNode.style.textAlign){..}
Which makes the function convertContent available. The result of which is an Object e.g.
JSON.stringify( convertContent($('<p>Word!</p>)[0]) )
Results in -
"{"string":
"<w:body>
<w:p>
<w:r>
<w:t xml:space=\"preserve\">Word!</w:t>
</w:r>
</w:p>
</w:body>"
,"charSpaceCount":5
,"charCount":5,
"pCount":1}"
I copied
<w:body>
<w:p>
<w:r>
<w:t xml:space="preserve">Word!</w:t>
</w:r>
</w:p>
</w:body>
into Notepad++ and saved it as a file with an extension of 'docx' but when I open it in MS Word but it says 'cannot be opened because there is a problem with the contents'.
Am I missing some attribute or XML tags or something?
You can generate a Docx Document from a template using docxtemplater (library I have created).
It can replace tags by their values (like a template engine), and also replace images in a paid version.
Here is a demo of the templating engine: https://docxtemplater.com/demo/
This code can't work on a JSFiddle because of the ajaxCalls to local files (everything that is in the blankfolder), or you should enter all files in ByteArray format and use the jsFiddle echo API: http://doc.jsfiddle.net/use/echo.html
I know this is an older question and you already have an answer, but I struggled getting this to work for a day, so I thought I'd share my results.
Like you, I had to fix the textAlign bug by changing the line to this:
if (inNode.style && inNode.style.textAlign)
Also, it didn't handle HTML comments. So, I had to add the following line above the check for a "#text" node in the for loop:
if (inNodeChild.nodeName === '#comment') continue;
To create the docx was tricky since there is absolutely no documentation on this thing as of yet. But looking through the code, I see that it is expecting the HTML to be in a File object. For my purposes, I wanted to use the HTML I rendered, not some HTML file the user has to select to upload. So I had to trick it by making my own object with the same property that it was looking for and pass it in. To save it to the client, I use FileSaver.js, which requires a blob. I included this function that converts base64 into a blob. So my code to implement it is this:
var result = docx({ DOM: $('#myDiv')[0] });
var blob = b64toBlob(result.base64, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
saveAs(blob, "test.docx");
In the end, this would work for simple Word documents, but isn't nearly sophisticated for anything more. I couldn't get any of my styles to render and I didn't even attempt to get images working. I've since abandoned this approach and am now researching DocxgenJS or some server-side solution.
You may find this link useful,
http://evidenceprime.github.io/html-docx-js/
An online demo here:
http://evidenceprime.github.io/html-docx-js/test/sample.html
You are doing the correct thing codewise, but your file is not a valid docx file. If you look through the docx() function in docx.js, you will see that a docx file is actually a zip containing several xml files.
I am using Open Xml SDK for JavaScript.
http://ericwhite.com/blog/open-xml-sdk-for-javascript/
Basically, on web server, I have a empty docx file as new template.
when user in browser click new docx file, I will retrieve the empty docx file as template, convert it to BASE64 and return it as Ajax response.
in client scripts, you convert the BASE64 string to byte array and using openxmlsdk.js to load the byte array as an javascript OpenXmlPackage object.
once you have the package loaded, you can use regular OpenXmlPart to create a real document. (inserting image, creating table/row ).
the last step is stream it out to end user as a document. this part is security related. in my code I send it back to webserver and gets saved temporarily. and prepare a http response to notify end user to download it.
Check the URL above, there are useful samples of doing this in JavaScript.
How to validate the content-type of a file before uploading using JavaScript? I'm not asking the extension validation. I want to validate pdf,plain text and MS word files.
I'm using a django forms.ModelForm to pass file upload widget to html. I couldn't achieve this either on server side. Here is that question,
Django - Uploaded file type validation
Maybe but it won't give you any form of security because an attacker could use other means to upload files thus circumventing your validation.
To check the file type using the extension (which is very insecure since it's dead easy to manipulate it), you can use JavaScript. See this question: How do I Validate the File Type of a File Upload?
[EDIT] After some googling, I found that the input element has an attribute accept which takes a list of mime type patterns. Unfortunately, most browsers ignore it (or only use it to tweak the file selection dialog). See this question: File input 'accept' attribute - is it useful?
[EDIT 2] Right now, it seems that the File API (see "Using files from web applications") is your only way it you really don't want to use file extensions. Each File instance has a type property which contains the mime type.
But this API is work in progress, so it's not available everywhere. And there is no guarantee that you'll get a MIME type (the property can be "").
So I suggest this approach: Try the File API. If it's not available or the type property is empty, use the file extension.
In theory you could use the File API to read the files.
You would then need to write parsers in JavaScript for the file formats you cared about to check if they matched.
I'm using uploadify + s3, and when trying to upload a file that has question marks in it, Uploadify doesn't give me the correct filename. For example, if the file is named #?? (copy).mp4, the fileObj.name value sent to the event handlers is # (basically everything after and including the question mark is removed).
Ignoring the original filename altogether is not an option, because I also need the extension.
If I try to change the scriptData at runtime, the upload will fail for some reason.
Can you help me out with this issue?
The problem exists above uploadify in actionscript's FileReference object.
From what I can tell the FileReference object chops the name at the question mark and only returns the part in front it.
I tried finding some way of getting to the original filesystem file name before it populated FileReference(event.target).name but I have next to no knowledge of actionscript.
I've also thought about renaming on the server but no mime type is set when the file is uploaded due to how `FileReference' handles the filename. I think it throws away the file ext since it's after the question mark.
I looked into hacking the uploadify Javascript to deal with file name validation and sanitization client side or send something to the server so the name can be fixed when the file is processed but by by the time uploadify has access to the name it's been truncated.