Как воспроизвести видео в формате mp4 в теге html video, в котором видео загружается через Multer
Я должен воспроизводить видео на моем сайте. Видео загружается через мультер с помощью node.js и в Express Framework. Файл вставляется в базу данных и указанную папку (имя файла, например, 1b47c24b20cc2465fbcb395fd1a9dfb4). Я также загружаю изображение и оно отображается правильно, но видео не воспроизводится.
Вот мой HTML код
Пожалуйста, помогите мне найти решение. и что такое файл .ogg, как я могу сгенерировать при загрузке моего видео?
user1187 19 Май 2017 в 20:27
2 ответа
Лучший ответ
При загрузке через Multer, пожалуйста, включите расширение.
var storage = multer.diskStorage(< destination: function (req, file, cb) < cb(null, 'public/images') >, filename: function (req, file, cb) < let extArray = file.mimetype.split("/"); let extension = extArray[extArray.length - 1]; cb(null, file.fieldname + '-' + Date.now()+ '.' +extension) >>)
И при отображении через угловой используйте код ниже
Угловой под контроллер
$scope.getVideoUrl=function(videopath) < return $sce.trustAsResourceUrl("/images/"+videopath); >;
Не забудьте включить $ sce
user1187 30 Май 2017 в 17:34
К сожалению, для отображения видео в разных браузерах нужны разные расширения видео. Здесь вы найдете список поддерживаемых форматов видео в браузерах https://www.w3schools.com /html/html5_video.asp Поэтому вам также необходимо конвертировать видео на стороне сервера в два недостающих формата (если вы хотите поддерживать все браузеры). Если (как вы сказали) вместо загрузки встроенного проигрывателя загружается видео, это означает, что ваш браузер не поддерживает этот конкретный формат видео.
К счастью, вы можете установить ffmpeg на свой сервер и проанализировать его с помощью библиотеки-оболочки.
Обратите внимание на препятствия — если ничего не изменилось, библиотека очень часто возвращает «готово», когда файл анализируется, но не сохраняется на жестком диске, поэтому вы не можете получить к нему доступ немедленно, но с задержкой в миллисекундах.
Работа с аудио и видео node JS
Запускаю сервер на node JS, почему я не могу воспроизвести видео и аудио на этой странице, видел кусок кода, где в потоке отправлялось видео с сервера. Мой вопрос: как сделать, чтобы видео и аудио все же воспроизводилось. Пишу на Node JS 2 день, ничего годного в интернете не нашел, как реализовать, поэтому уважаемые комментаторы не судите строго) Есть html страница:
Хоккейная экипировка Хоккейная экипировка Контакты Галерея Главное меню Каталог О компании
Видео о хоккее Музыка о хоккее
var http = require("http"); var url = require("url"); var fs = require('fs'); var mysql = require('mysql'); var path = require('path'); formidable = require('formidable'); function onServer(route, newServer, reqtype) < function onRequest(request, response)< var pathname = url.parse(request.url).pathname; try catch (err)<> if(request.method === 'GET') get(request, response, pathname); if (request.method === 'POST') post(request, response, pathname); else < if (pathname !== "favicon.ico") < openPage(response, pathname); >> > function openPage(response, pathname)< var path = route(pathname); var html = ""; html = newServer(path); var type = reqtype(path); response.writeHead(302, ); response.write(html); response.end(); > function get(request, response, pathname)< switch(pathname)< case "audio/music.ogg": var filePath = path.join(__dirname, 'audio/music.ogg'); var stat = fileSystem.statSync(filePath); response.writeHead(200, < 'Content-Type': 'audio/ogg', 'Content-Length': stat.size >); var readStream = fileSystem.createReadStream(filePath); readStream.pipe(response); break; case "video/ska.ogv": var filePath = path.join(__dirname, 'video/ska.ogv'); var stat = fileSystem.statSync(filePath); response.writeHead(200, < 'Content-Type': 'video/ska.ogv', 'Content-Length': stat.size >); var readStream = fileSystem.createReadStream(filePath); readStream.pipe(response); break; default: console.log("Uncorrect choice"); > > function post(request, response, pathname) < switch(pathname)< case "registration.html": var form = new formidable.IncomingForm(); form.parse(request, function(err, params, files)< connection.query("INSERT INTO users (login, password) VALUES (. )", [params["login"],params["userpass"]], function(err, result) < if (!err) < console.log('new registration'); openPage(response, "successfulRegistration.html"); >else console.log(err.message); >); >); break; case "autorization.html": var form = new formidable.IncomingForm() form.parse(request, function(err, params, files) < connection.query('SELECT * from users', params, function(err, rows, fields)< if (!err)< for (var i = 0; i < rows.length; i++)< if (rows[i].login === params.login && rows[i].password === params.password)< console.log('5'); console.log('authorization'); openPage(response, "home.html"); return 0; >else < openPage(response, "unsuccessfulRegistration.html"); return 0; >> console.log(params); > >); >); break; case "server.js": fs.readFile('txt/company.txt', 'utf8', function(err, data) < if(err)< console.log(err); >else < console.log(data); response.write(data); response.end(); >>); break; case "audio/music.ogg": var filePath = path.join(__dirname, 'audio/music.ogg'); var stat = fileSystem.statSync(filePath); response.writeHead(200, < 'Content-Type': 'audio/ogg', 'Content-Length': stat.size >); var readStream = fileSystem.createReadStream(filePath); readStream.pipe(response); break; case "video/ska.ogv": var filePath = path.join(__dirname, 'video/ska.ogv'); var stat = fileSystem.statSync(filePath); response.writeHead(200, < 'Content-Type': 'video/ska.ogv', 'Content-Length': stat.size >); var readStream = fileSystem.createReadStream(filePath); readStream.pipe(response); break; default: console.log("Uncorrect choice"); > > http.createServer(onRequest).listen(5656); console.log("Server started on port 5656"); >; exports.onServer = onServer;
Converting video to .mp4 with Node.js
Well, for one converter converts between xml , json , and yaml . So, you won’t be able to convert an avi to an mp4 with that.
However, I have used node to spawn a child ffmpeg process for this very thing. Just an fyi, if you do choose to use ffmpeg via a child process and want to watch the log for progress and debugging, you will need to watch stderr . Ffmpeg reserves stdout to optionally stream the output of the conversion.
answered Jun 27, 2014 at 16:49
4,323 5 5 gold badges 30 30 silver badges 51 51 bronze badges
FFMPEG is good thing for play with video.
Try this command.
exec("ffmpeg -i filePath/fileName.ext filePath/newFileName.mp4");
You can set your other preset also.
Using Nodejs to Serve an MP4 Video File
I am trying to serve a ~52MB mp4 video file from a nodejs server. Attached below is a screenshot of the code used to serve the file. I have an object of mime types for static file calls which contains the mime type for mp4. var mimeTypes = < html: 'text/html; charset=utf-8', jpeg: 'image/jpeg', jpg: 'image/jpeg', png: 'image/png', js: 'text/javascript', css: 'text/css', mp4: 'video/mp4' >; However, when I try to navigate to the page in chrome, I get the error: GET http://localhost:8888/videos/movie.mp4 net::ERR_INCOMPLETE_CHUNKED_ENCODING Now this same logic (screenshotted above) is used to serve images and css just fine, however it fails miserably when trying to serve the mp4. Looking at the network requests panel in Chrome, I can see that the server responded with a 200 OK status, and served a zero byte file as the video. The range of bytes in the network request also looks suspicious but I don’t know enough about HTTP requests to know for sure.
Looking at the stats object (shown below, gotten from fs.lstat), It appears that the file ‘knows’ how to be split into chunks of 4096 bytes, however I keep getting the incomplete chunked encoding error. I have no antivirus, and tried turning off various settings in Chrome/using another browser but I can’t see the video. Is there a header I am missing? Am I somehow ending the response too early? I’m clueless right now.
asked Jun 16, 2016 at 18:33
903 4 4 gold badges 12 12 silver badges 30 30 bronze badges
Do not post screenshots of code; copy and paste the actual code and format it correctly.
Jun 16, 2016 at 19:29
3 Answers 3
This is what I used for my project.
answered Jun 16, 2016 at 19:26
1,466 15 15 silver badges 27 27 bronze badges
This was enough with me. MP4 has native support for strimming (pseudo streaming). It worked very well for watching videos in the browser via streaming.
res.setHeader('Content-Type', 'video/mp4'); res.status(200).sendFile(full_path, function (err) < if (err) < . >else < . >>);
answered Feb 19, 2020 at 15:11
Vinicius Castro Vinicius Castro
31 1 1 bronze badge
Thanks , it works for me . I only need a simple local development test, so I used this simple and easy method.
