I have written a upload tool with html5.
I create a file path with URL.createObjectURL(file); // file = a file from filelist -> dataTransfer (input multifile select)
<div class='photo' style='background:url(" + Link + ") center center; background-size:cover'></div>
Now will I be able to read the file infos with the old method (file reader)
file = $('.Foto').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/,'');
console.log(file); //blob:http://localhost/16264d2d-572e-4f3c-88cb-9d081147ed3a
reader.readAsArrayBuffer(file);
Now I am getting an error from firebug:
"TypeError: Argument 1 of FileReader.readAsArrayBuffer is not an object"
the self error with:
readAsBinaryString()
readAsDataURL()
readAsText()
I need this for other informations from the file:
example: file.size, file.name, file.type
I will upload big files in blobs:
fileb = file.slice(start,end);
formData.append("afile",fileb);
xhr.open("POST", Link, true);
xhr.send(formData);
My problem is, I need a upload tool with multifile select and multi drop (dropzone). The files are only uploaded, when the user click on the button "now upload the files".
The big problem is the html5 API filelist.
When I select new files with drap and drop or file explorer, is the old list empty.
Can I merge (push) new files to the filelist?
Related
I use Firebase to generate a download link in AngularJS as follows:
self.getDownloadUrl = function(storage_ref) {
var q = $q.defer();
var storage = firebase.storage();
storage.ref(storage_ref).getDownloadURL().then(function(url) {
q.resolve(url);
}).catch(function(error) {
q.reject(error);
});
return q.promise;
};
Then I bind the url to an object scope.downloadUrl. In my DOM I then try to download the file as follows:
Download
However, when I click on this link, it opens my .csv file in the browser (looks like a text file with comma separated, tested it on Chrome and Edge). How can I prevent this and just enforce a proper download?
I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment
I'm using the following when trying to open a local file:
some document
When I click the above in a browser, it opens Finder to the folder. But does not open the file. Should I be doing something else to have the file open in Numbers?
You cannot open local files on the client. This would be a huge security risk.
You can link to files on your server (like you did) or you can ask the client for a file using <input type="file">
You can only open some types of files in browsers, like html css js and mp4, otherwise the browser will want to download it. Also remember that browsers replace spaces with %20. I recommend right clicking the file and opening it with chrome then copy that link and using it.
You can open files that are local as long as it is a file that is on the file that is trying to open another file is local.
Your issue is likely the space in the document name. Try this instead:
some document
The %20 will be read by your browser as a space.
Update
The other answer points out something I missed. The .numbers extension will not be able to be opened directly by your browser. Additionally the other answer describes the security risk this could create.
The File API in HTML 5 now allows you to work with local files directly from JS (after basic user interaction in selecting the file(s), for security).
From the Mozilla File API docs:
"The File interface provides information about files and allows JavaScript in a web page to access their content.
File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement."
For more info and code examples, see the sample demo linked from the same article.
This might not be what you're trying to do, but someone out there may find it helpful:
If you want to share a link (by email for example) to a network file you can do so like this:
file:///Volumes/SomeNetworkFolder/Path/To/file.html
This however also requires that the recipient connects to the network folder in finder --- in menu bar,
Go > Connect to Server
enter server address (e.g. file.yourdomain.com - "SomeNetworkFolder" will be inside this directory) and click Connect. Now the link above should work.
Here is the alternative way to download local file by client side and server side effort:
<a onclick='fileClick(this)' href="file://C:/path/to/file/file.html"/>
js:
function fileClick(a) {
var linkTag = a.href;
var substring = "file:///";
if (linkTag.includes(substring)) {
var url = '/v/downloadLocalfile?path=' +
encodeURIComponent(linkTag);
fileOpen(url);
}
else {
window.open(linkTag, '_blank');
}
}
function fileOpen(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log("Complete: [ " + txt_status + " ] " + jqxhr);
if (txt_status == 'success') {
window.open(url, '_self');
}
else {
alert("File not found[404]!");
}
// }
}
});
}
Server side[java]:
#GetMapping("/v/downloadLocalfile")
public void downloadLocalfile(#RequestParam String path, HttpServletResponse
response) throws IOException, JRException {
try {
String nPath = path.replace("file:///", "").trim();
File file = new File(nPath);
String fileName = file.getName();
response.setHeader("Content-Disposition", "attachment;filename=" +
fileName);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
response.setStatus(200);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
// out.flush();
in.close();
out.close();
}
else {
response.setStatus(404);
}
} catch (Exception ex) {
logger.error(ex.getLocalizedMessage());
}
return;
}
You can expose your entire file system in your browser by using an http server.
caddy2 server
caddy file-server --listen :2022 --browse --root /
serves the root file system at http://localhost:2022/
python3 built-in server
python3 -m http.server
serves current dir on http://localhost:8000/
python2 built-in server
python3 -m SimpleHTTPServer
serves current dir on http://localhost:8000/
This s
I have an issue with sending a file (part of a request in form data format).
The issue seems coming from the fact that only in Chrome for Linux the file (which is CVS file, with .csv extension and basically just text) is sent with mimetype (Content-type in request body) Content-Type: application/octet-stream
So, I am trying to override the mimetype to match the same sent by Chrome on Linux which is text/csv.
However the mimetype is apparently not overriden and still send as octet-stream.
My code:
let xhr = new XMLHttpRequest();
let form = new FormData();
form.append('file', file, file.name); // the file is loaded correctly
form.append('payload', JSON.stringify(data)); // data is just a JSON object
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
// we arrive here both on Debian and Windows 10
}
}
xhr.upload.onerror = function() { .... } // no error
xhr.open('POST', 'http://<my_url>', true);
console.log(file.type);
xhr.overrideMimeType("text/csv");
xhr.send(form);
A couple of notes:
console.log(file.type) actually prints "text-csv" but only in Chrome for Linux (Debian specifically). in the other cases (any other browser or platform) nothing is printed
given the previous point, it seems clear to me for some reason any other browser / platform can't recognize the file type, so the file is sent as octet-stream (general binary file)
xhr.overrideMimeType changes the MIME-type of the response, not the request.
I you want to change the MIME-type of the file, just create a new Blob with an explicit file type:
var blob = new Blob([blob], {type: 'text/csv'});
form.append('file', blob, file.name);
The above changes the MIME-type of the file in the uploaded form to "text/csv", as desired.
PS. If you literally want to change the MIME-type of the whole request (instead of just the file), use xhr.setRequestHeader('Content-Type', 'custom MIME type here');. (This only makes sense if you are sending a non-standard or custom data in the xhr.send method).
I am trying to create an extension which puts all the pdf files downloaded by user through browser into a separate directory. Any Api by which can do this or some help on how I can do it would be helpful.
While you cannot easily write to an arbitrary path, you can redirect all PDF files into a subfolder of Downloads folder.
Check out onDeterminingFilename event of chrome.downloads and Filename Controller sample extension. Since you can indicate a relative path instead of a plain filename, this should work.
Note that the file's MIME type should be available in onDeterminingFilename, you can use that.
Code example, as requested:
var folder = "PDF_downloads";
chrome.downloads.onDeterminingFilename.addListener(
function (item, suggest) {
if(isPDF(item)) suggest({filename: folder + "/" + item.filename});
else suggest();
}
);
function isPDF(item){
if(item.mime === "application/pdf") return true;
else if (item.filename.match(/\.pdf$/i)) return true;
else return false;
}
This will not override that the browser tries to open the PDF itself instead of downloading, but attempting to download will suggest that folder.