How to get file name from content-disposition - javascript

I downloaded a file as response of ajax. How to get the file name and file type from content-disposition and display thumbnail for it. I got many search results but couldn't find right way.
$(".download_btn").click(function () {
var uiid = $(this).data("id2");
$.ajax({
url: "http://localhost:8080/prj/" + data + "/" + uiid + "/getfile",
type: "GET",
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
success: function (response, status, xhr) {
var header = xhr.getResponseHeader('Content-Disposition');
console.log(header);
}
});
Console output:
inline; filename=demo3.png

Here is how I used it sometime back.
I'm assuming you are providing the attachment as a server response.
I set the response header like this from my REST service response.setHeader("Content-Disposition", "attachment;filename=XYZ.csv");
function(response, status, xhr){
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
}
EDIT:
Editing the answer to suit your question- use of the word inline instead of attachment
function(response, status, xhr){
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('inline') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
}
More here

This is an improvement on marjon4's answer.
A much simplified way to the selected answer would be to use split like this;
var fileName = xhr.getResponseHeader('content-disposition').split('filename=')[1].split(';')[0];
Note: This solution may not work as expected if your file name itself contains a semi-colon (;)

If you want to get the filename and support both those weird url encoded UTF-8 headers and the ascii headers, you can use something like this
public getFileName(disposition: string): string {
const utf8FilenameRegex = /filename\*=UTF-8''([\w%\-\.]+)(?:; ?|$)/i;
const asciiFilenameRegex = /^filename=(["']?)(.*?[^\\])\1(?:; ?|$)/i;
let fileName: string = null;
if (utf8FilenameRegex.test(disposition)) {
fileName = decodeURIComponent(utf8FilenameRegex.exec(disposition)[1]);
} else {
// prevent ReDos attacks by anchoring the ascii regex to string start and
// slicing off everything before 'filename='
const filenameStart = disposition.toLowerCase().indexOf('filename=');
if (filenameStart >= 0) {
const partialDisposition = disposition.slice(filenameStart);
const matches = asciiFilenameRegex.exec(partialDisposition );
if (matches != null && matches[2]) {
fileName = matches[2];
}
}
}
return fileName;
}
A couple of notes:
this will take the value of the UTF-8 filename, if set, over the ascii name
on download, your browser may further alter the name to replace certain characters, like ", with _ (Chrome)
the ascii pattern works best for quoted file names, but supports unquoted values. In that case it treats all text after the filename= and before the either the next ; or the end of the header value as the file name.
This does not clean up path information. If you are saving the file from a website, that's the browser's job, but if your using this in the context of a node app or something similar, be sure to clean up the path information per the OS and leave just the filename, or a crafted file name might be used to overwrite a system file (think of a file name like ../../../../../../../path/to/system/files/malicious.dll)
MDN Content Disposition Header

Or simply just:
var fileName = xhr.getResponseHeader('Content-Disposition').split("filename=")[1];

In my case the header looks like this:
attachment; filename="test-file3.txt"
Therefore I was able to extract the filename pretty easily with a named group regexp:
const regExpFilename = /filename="(?<filename>.*)"/;
const filename: string | null = regExpFilename.exec(contentDispositionHeader)?.groups?.filename ?? null;
I know I'm slightly off topic here as OP doesn't have the quotes around the filename but still sharing in case someone comes across the same pattern as I just did

Try this solution:
var contentDisposition = xhr.getResponseHeader('Content-Disposition');
var startIndex = contentDisposition.indexOf("filename=") + 10; // Adjust '+ 10' if filename is not the right one.
var endIndex = contentDisposition.length - 1; //Check if '- 1' is necessary
var filename = contentDisposition.substring(startIndex, endIndex);
console.log("filename: " + filename)

There is an npm package that does the job: content-disposition

I believe this will help!
let filename = response.headers['content-disposition'].split('filename=')[1].split('.')[0];
let extension = response.headers['content-disposition'].split('.')[1].split(';')[0];

There's also library content-disposition-attachment, which can be used in the browser:
npm i -D content-disposition-attachment
import { AxiosResponse } from "axios";
import { parse } from "content-disposition-attachment";
const getFilenameFromHeaders = ({ headers }: AxiosResponse<Blob>) => {
const defaultName = "untitled";
try {
const { attachment, filename } = parse(headers["content-disposition"]);
return attachment ? filename : defaultName;
} catch (e) {
console.error(e);
return defaultName;
}
};

The below also takes into account scenarios where the filename includes unicode characters (i.e.,-, !, (, ), etc.) and hence, comes (utf-8 encoded) in the form of, for instance, filename*=utf-8''Na%C3%AFve%20file.txt (see here for more details). In such cases, the decodeURIComponent() function is used to decode the filename.
const disposition = xhr.getResponseHeader('Content-Disposition');
filename = disposition.split(/;(.+)/)[1].split(/=(.+)/)[1]
if (filename.toLowerCase().startsWith("utf-8''"))
filename = decodeURIComponent(filename.replace("utf-8''", ''))
else
filename = filename.replace(/['"]/g, '')
If you are doing a cross-origin request, make sure to add Access-Control-Expose-Headers: Content-Disposition to the response headers on server side (see Access-Control-Expose-Headers), in order to expose the Content-Disposition header; otherwise, the filename won't be accessible on client side through JavaScript. For instance:
headers = {'Access-Control-Expose-Headers': 'Content-Disposition'}
return FileResponse("Naïve file.txt", filename="Naïve file.txt", headers=headers)

If you are not working with multipart body then you can use this function. It extracts the filename from the Content-Disposition header value (string like: inline; filename=demo3.png) and decodes as needed.
const getFileNameFromContentDisposition = disposition => {
if (disposition
&& (disposition.startsWith('attachment') || disposition.startsWith('inline'))
) {
let filename = disposition.startsWith('attachment')
? disposition.replace("attachment;", "")
: disposition.replace("inline;", ""); //replaces first match only
filename = filename.trim();
if (filename.includes("filename*=") && filename.includes("filename=")) {
let filenames = filename.split(";"); //we can parse by ";" because all ";"s inside filename are escaped
if (filenames.length > 1) { //"filename=" or "filename*=" not inside filename
if (filenames[0].trim().startsWith("filename*=")) { //"filename*=" is preferred
filename = filenames[0].trim();
} else {
filename = filenames[1].trim();
}
}
}
if (filename.startsWith("filename*=")) {
filename = filename.replace("filename*=", "")
.split("''").slice(1).join("''"); //remove encoding and ''
filename = decodeURIComponent(filename);
} else if (filename.startsWith("filename=")) {
filename = filename.replace("filename=", "")
if (filename.startsWith('"') && filename.endsWith('"')) {
filename = filename.slice(1, filename.length - 1); //remove quotes
}
}
return filename;
}
}
The result of the function can be split into name and extension as follows:
let name = getFileNameFromContentDisposition("inline; filename=demo.3.png").split(".");
let extension = name[name.length - 1];
name = name.slice(0, name.length - 1).join(".");
console.log(name); // demo.3
console.log(extension); //png
You can display thumbnail, for example, using svg:
let colors = {"png": "red", "jpg": "orange"};
//this is a simple example, you can make something more beautiful
let createSVGThumbnail = extension => `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" viewBox="0 0 18 20">
<rect x="0" y="0" width="18" height="20" fill = "#FAFEFF"/>
<rect x="0" y="7" width="18" height="6" stroke="${colors[extension] || "blue"}" fill = "${colors[extension] || "blue"}"/>
<text stroke = "white" fill = "white" font-size = "6" x = "0" y = "12.5" textLength = "18">${extension.toUpperCase()}</text>
</svg>`;
...
//You can use it as HTML element background-image
let background = "data:image/svg+xml;base64," + btoa(new TextDecoder().decode(createSVGThumbnail("png")));

Related

Ajax file download sets filename to random string of characters

I am trying to download a file using ajax. The download works correctly, however, the downloaded filename is set to a random string of characters. I don't think this is relevant since the backend is working, but I'm using django
js/html:
<script>
function downloadFile(){
var filename = 'data.txt';
$.ajax({
url: 'downloadFile',
data: {'filename': filename},
success: function(blob, status, xhr){
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') != -1){
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]){
filename = matches[1].replace(/['"]/g,'');
}
}
var bd = [];
bd.push(blob);
var typename = "application/" + filename;
var downloadURL = window.URL.createObjectURL(new Blob(bd, {type: typename}));
var a = document.createElement("a");
a.href = downloadURL;
document.body.append(a);
a.click();
}
});
}
</script>
...
<button id="downloadFile" type="button" onclick="downloadFile()"><i class="fa fa-download"></i></button>
...
django views.py:
import pathlib
import os
def downloadFile(request):
fname = request.GET.get('filename')
fpath = os.path.join(<local_filesystem_path>, fname)
# code to generate file here
if pathlib.Path(fpath).exists():
file_download = open(fpath, 'rb')
response = HttpResponse(file_download, content_type='application/{}'.format(fname))
response['Content-Disposition'] = 'attachment; filename="{}"'.format(fname)
return response
and urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('downloadFile', views.downloadFile, name='downloadFile')
]
When I click the download button, everything works correctly except that my file has been renamed to a random string of 8 characters. Each time I re-download it, the string changes, but it's always 8 characters long. I'm guessing that something is happening where my browser thinks that the filename is unset so it's assigning a random string. But I'd like to set it to something I've specified - how can I do this?
Try adding a download attribute to the the <a> tag that you create. It allows you to set the file name.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download

How to get avatar file type [duplicate]

How do I find the file extension of a URL using javascript?
example URL:
http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294
I just want the 'swf' of the entire URL.
I need it to find the extension if the url was also in the following format
http://www.adobe.com/products/flashplayer/include/marquee/design.swf
Obviously this URL does not have the parameters behind it.
Anybody know?
Thanks in advance
function get_url_extension( url ) {
return url.split(/[#?]/)[0].split('.').pop().trim();
}
example:
get_url_extension('https://example.com/folder/file.jpg');
get_url_extension('https://example.com/fold.er/fil.e.jpg?param.eter#hash=12.345');
outputs ------> jpg
Something like this maybe?
var fileName = 'http://localhost/assets/images/main.jpg';
var extension = fileName.split('.').pop();
console.log(extension, extension === 'jpg');
The result you see in the console is.
jpg true
if for some reason you have a url like this something.jpg?name=blah or something.jpg#blah then you could do
extension = extension.split(/\#|\?/g)[0];
drop in
var fileExtension = function( url ) {
return url.split('.').pop().split(/\#|\?/)[0];
}
For the extension you could use this function:
function ext(url) {
// Remove everything to the last slash in URL
url = url.substr(1 + url.lastIndexOf("/"));
// Break URL at ? and take first part (file name, extension)
url = url.split('?')[0];
// Sometimes URL doesn't have ? but #, so we should aslo do the same for #
url = url.split('#')[0];
// Now we have only extension
return url;
}
Or shorter:
function ext(url) {
return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('#')[0].substr(url.lastIndexOf("."))
}
Examples:
ext("design.swf")
ext("/design.swf")
ext("http://www.adobe.com/products/flashplayer/include/marquee/design.swf")
ext("/marquee/design.swf?width=792&height=294")
ext("design.swf?f=aa.bb")
ext("../?design.swf?width=792&height=294&.XXX")
ext("http://www.example.com/some/page.html#fragment1")
ext("http://www.example.com/some/dynamic.php?foo=bar#fragment1")
Note:
File extension is provided with dot (.) at the beginning. So if result.charat(0) != "." there is no extension.
This is the answer:
var extension = path.match(/\.([^\./\?]+)($|\?)/)[1];
Take a look at regular expressions. Specifically, something like /([^.]+.[^?])\?/.
// Gets file extension from URL, or return false if there's no extension
function getExtension(url) {
// Extension starts after the first dot after the last slash
var extStart = url.indexOf('.',url.lastIndexOf('/')+1);
if (extStart==-1) return false;
var ext = url.substr(extStart+1),
// end of extension must be one of: end-of-string or question-mark or hash-mark
extEnd = ext.search(/$|[?#]/);
return ext.substring (0,extEnd);
}
url.split('?')[0].split('.').pop()
usually #hash is not part of the url but treated separately
This method works fine :
function getUrlExtension(url) {
try {
return url.match(/^https?:\/\/.*[\\\/][^\?#]*\.([a-zA-Z0-9]+)\??#?/)[1]
} catch (ignored) {
return false;
}
}
You can use the (relatively) new URL object to help you parse your url. The property pathname is especially useful because it returns the url path without the hostname and parameters.
let url = new URL('http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294');
// the .pathname method returns the path
url.pathname; // returns "/products/flashplayer/include/marquee/design.swf"
// now get the file name
let filename = url.pathname.split('/').reverse()[0]
// returns "design.swf"
let ext = filename.split('.')[1];
// returns 'swf'
var doc = document.location.toString().substring(document.location.toString().lastIndexOf("/"))
alert(doc.substring(doc.lastIndexOf(".")))
const getUrlFileType = (url: string) => {
const u = new URL(url)
const ext = u.pathname.split(".").pop()
return ext === "/"
? undefined
: ext.toLowerCase()
}
function ext(url){
var ext = url.substr(url.lastIndexOf('/') + 1),
ext = ext.split('?')[0],
ext = ext.split('#')[0],
dot = ext.lastIndexOf('.');
return dot > -1 ? ext.substring(dot + 1) : '';
}
If you can use npm packages, File-type is another option.
They have browser support, so you can do this (taken from their docs):
const FileType = require('file-type/browser');
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const response = await fetch(url);
const fileType = await FileType.fromStream(response.body);
console.log(fileType);
//=> {ext: 'jpg', mime: 'image/jpeg'}
})();
It works for gifs too!
Actually, I like to imporve this answer, it means my answer will support # too:
const extExtractor = (url: string): string =>
url.split('?')[0].split('#')[0].split('.').pop() || '';
This function returns the file extension in any case.
If you wanna use this solution. these packages are using latest import/export method.
in case you wanna use const/require bcz your project is using commonJS you should downgrade to older version.
i used
"got": "11.8.5","file-type": "16.5.4",
const FileType = require('file-type');
const got = require('got');
const url ='https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const stream = got.stream(url);
console.log(await FileType.fromStream(stream));
})();
var fileExtension = function( url ) {
var length=url.split(?,1);
return length
}
document.write("the url is :"+length);

get file name of selected file

How can I get only the name of the selected Data. I do the following but get the whole path of the File. I would like to display the filename for the user
var dialog = require('electron').remote.dialog;
var url;
document.getElementById('openButton').onclick = () => {
dialog.showOpenDialog((fileName) => {
if(fileName === undefined) {
alert('No file selected');
} else {
console.log(fileName)
url = fileName[0];
console.log(url);
$('#dataFileName').html(url)
}
})
};
What i get is "/Users/void/Desktop/abc.xlsx" and I would like to have in addition to that only the file i opened.
You can also use path.basename()
const {basename} = require('path')
let filePath = "/Users/void/Desktop/abc.xlsx"
let fileName = basename(filePath)
Here is a simple way you can grab just the file name:
var filePath = "/Users/void/Desktop/abc.xlsx";
var fileName = filePath.replace(/^.*[\\\/]/, '');
console.log(fileName);
Here is a fiddle to demonstrate.
If I understood correctly, you can use this:
var mystring = "/Users/void/Desktop/abc.xlsx"; //replace your string
var temp = mystring.split("/"); // split url into array
var fileName = temp[temp.length-1]; // get the last element of the array
What you basically do is to split your url with "/" regex, so you get each bit, and filename is always the last bit so you can get it with array's length you just created.

Client download of a server generated zip file

Before somebody says, "duplicate", I just want to make sure, that folks know, that I have already reviewed these questions:
1) Uses angular and php, not sure what is happening here (I don't know PHP): Download zip file and trigger "save file" dialog from angular method
2) Can't get this answer to do anything: how to download a zip file using angular
3) This person can already download, which is past the point I'm trying to figure out:
Download external zip file from angular triggered on a button action
4) No answer for this one:
download .zip file from server in nodejs
5) I don't know what language this even is:
https://stackoverflow.com/questions/35596764/zip-file-download-using-angularjs-directive
Given those questions, if this is still a duplicate, I apologize. Here is, yet, another version of this question.
My angular 1.5.X client gives me a list of titles, of which each have an associated file. My Node 4.X/Express 4.X server takes that list, gets the file locations, creates a zip file, using express-zip from npm, and then streams that file back in the response. I then want my client to initiate the browser's "download a file" option.
Here's my client code (Angular 1.5.X):
function bulkdownload(titles){
titles = titles || [];
if ( titles.length > 0 ) {
$http.get('/query/bulkdownload',{
params:{titles:titles},
responseType:'arraybuffer'
})
.then(successCb,errorCb)
.catch(exceptionCb);
}
function successCb(response){
// This is the part I believe I cannot get to work, my code snippet is below
};
function errorCb(error){
alert('Error: ' + JSON.stringify(error));
};
function exceptionCb(ex){
alert('Exception: ' + JSON.stringify(ex));
};
};
Node (4.X) code with express-zip, https://www.npmjs.com/package/express-zip:
router.get('/bulkdownload',function(req,resp){
var titles = req.query.titles || [];
if ( titles.length > 0 ){
utils.getFileLocations(titles).
then(function(files){
let filename = 'zipfile.zip';
// .zip sets Content-Type and Content-disposition
resp.zip(files,filename,console.log);
},
_errorCb)
}
});
Here's my successCb in my client code (Angular 1.5.X):
function successCb(response){
var URL = $window.URL || $window.webkitURL || $window.mozURL || $window.msURL;
if ( URL ) {
var blob = new Blob([response.data],{type:'application/zip'});
var url = URL.createObjectURL(blob);
$window.open(url);
}
};
The "blob" part seems to work fine. Checking it in IE's debugger, it does look like a file stream of octet information. Now, I believe I need to get that blob into the some HTML5 directive, to initiate the "Save File As" from the browser. Maybe? Maybe not?
Since 90%+ of our users are using IE11, I test all of my angular in PhantomJS (Karma) and IE. When I run the code, I get the old "Access is denied" error in an alert window:
Exception: {"description":"Access is denied...<stack trace>}
Suggestions, clarifications, answers, etc. are welcome!
Use this one:
var url="YOUR ZIP URL HERE";
window.open(url, '_blank');
var zip_file_path = "" //put inside "" your path with file.zip
var zip_file_name = "" //put inside "" file name or something
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = zip_file_path;
a.download = zip_file_name;
a.click();
document.body.removeChild(a);
As indicated in this answer, I have used the below Javascript function and now I am able to download the byte[] array content successfully.
Function to convert byte array stream (type of string) to blob object:
var b64toBlob = function(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
};
An this is how I call this function and save the blob object with FileSaver.js (getting data via Angular.js $http.get):
$http.get("your/api/uri").success(function(data, status, headers, config) {
//Here, data is type of string
var blob = b64toBlob(data, 'application/zip');
var fileName = "download.zip";
saveAs(blob, fileName);
});
Note: I am sending the byte[] array (Java-Server-Side) like this:
byte[] myByteArray = /*generate your zip file and convert into byte array*/ new byte[]();
return new ResponseEntity<byte[]>(myByteArray , headers, HttpStatus.OK);
I updated my bulkdownload method to use $window.open(...) instead of $http.get(...):
function bulkdownload(titles){
titles = titles || [];
if ( titles.length > 0 ) {
var url = '/query/bulkdownload?';
var len = titles.length;
for ( var ii = 0; ii < len; ii++ ) {
url = url + 'titles=' + titles[ii];
if ( ii < len-1 ) {
url = url + '&';
}
}
$window.open(url);
}
};
I have only tested this in IE11.

In Node.js, given a URL, how do I check whether its a jpg/png/gif?

My current method is this:
var request = require('request');
var mime = require('mime');
var fs = require('fs');
var uri = 'http://www.sweetslyrics.com/images/img_gal/25646_christina-perri-213968.jpg';
request({
'method':'GET',
'uri': uri
},function(err, response,body){
var tmp_path = '/tmp/123456';
fs.writeFile(tmp_path, body, function(err) {
console.log(mime.lookup(tmp_path)); //application/octet-stream ?????
});
});
The image is obviously a picture, but node-mime says it's application/octet-stream. Why?
Note:
- I do not want to rely on the Response Headers content-type, because based on my experience, sometimes those response headers are set incorrectly...and they do not determine the true file type. (that's why I save it to a file, and then have node-mime determine it for me!)
I want to know the best way to determine if a file is an image, with 0 margin of error.
Edit: I just realized that node-mime isn't "magic". It just checks for the extension :( ...
Edit2: I found this: https://github.com/SaltwaterC/mime-magic
Just read the first bytes of the stream, and check it for the so called "magic number".
Magic numbers are the first bits of a file which uniquely identify the
type of file.
For example:
-Every JPEG file begins with ff d8 (hex).
-Every png file begins with a 89 50 4e 47.
-There is a comprehensive table of magic numbers here
This way even if you have a file without extension you can still detect its type.
Hope this helps.
This code shows a working solution for the magic numbers approach (summary of the existing answers and information on https://github.com/request/request).
var request = require('request');
var url = "http://www.somedomain.com/somepicture.jpg";
var magic = {
jpg: 'ffd8ffe0',
png: '89504e47',
gif: '47494638'
};
var options = {
method: 'GET',
url: url,
encoding: null // keeps the body as buffer
};
request(options, function (err, response, body) {
if(!err && response.statusCode == 200){
var magigNumberInBody = body.toString('hex',0,4);
if (magigNumberInBody == magic.jpg ||
magigNumberInBody == magic.png ||
magigNumberInBody == magic.gif) {
// do something
}
}
});
There are two modules that can help you achieve this:
https://github.com/SaltwaterC/mime-magic
https://github.com/bentomas/node-mime
In the intervening time since this question was first asked, mime-magic has become unsupported and its author recommends the use of mmmagic. I don't know what happened to node-mime, the link above is a 404. I found the following article which discusses the topic as well: https://nodejsmodules.org/tags/mime
i developped this code and i test it and it work for me you can use it
var express = require('express')
var app = express()
var http = require('http').Server(app).listen(80)
var upload = require('express-fileupload')
app.use(upload())
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/file.html")
})
app.post('/',(req,res)=>{
var options = {
method: 'GET',
url: req.files.filename,
encoding: null
}
if (req.files) {
if (req.files.filename.data.toString('hex',0,4) == '89504e47' || req.files.filename.data.toString('hex',0,4) == 'ffd8ffe0' || req.files.filename.data.toString('hex',0,4) == '47494638' ) {
var file = req.files.filename
filename = file.name
file.mv('./upload/'+filename,(err)=>{
if (err) {
console.log('small err')
} else {
res.send('DONE')
}
})
} else {
console.log('it not an image')
}
}
})

Categories

Resources