In my application, I want the user to record his video. Then the video should be downloaded to the Server disk. But it is downloading to the client browser. How can i save the 2 or 3 min video to the server. I have used getusermedia for this. I have written code like:
(function(exports) {
exports.URL = exports.URL || exports.webkitURL;
exports.requestAnimationFrame = exports.requestAnimationFrame ||
exports.webkitRequestAnimationFrame || exports.mozRequestAnimationFrame ||
exports.msRequestAnimationFrame || exports.oRequestAnimationFrame;
exports.cancelAnimationFrame = exports.cancelAnimationFrame ||
exports.webkitCancelAnimationFrame || exports.mozCancelAnimationFrame ||
exports.msCancelAnimationFrame || exports.oCancelAnimationFrame;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var ORIGINAL_DOC_TITLE = document.title;
var video = $('video');
var canvas = document.createElement('canvas');
var rafId = null;
var startTime = null;
var endTime = null;
function $(selector) {
return document.querySelector(selector) || null;
}
function toggleActivateRecordButton() {
var b = $('#record-me');
b.textContent = b.disabled ? 'Record' : 'Recording...';
b.classList.toggle('recording');
b.disabled = !b.disabled;
}
function turnOnCamera(e) {
e.target.disabled = true;
$('#record-me').disabled = false;
video.controls = false;
var finishVideoSetup_ = function() {
setTimeout(function() {
video.width = 320;
video.height = 240;
canvas.width = video.width;
canvas.height = video.height;
}, 1000);
};
navigator.getUserMedia({video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
finishVideoSetup_();
}, function(e) {
video.src = 'Chrome_ImF.mp4';
finishVideoSetup_();
});
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: true }, onRecordSucces, onFail);
} else {
console.log('navigator.getUserMedia not to present');
}
};
function record() {
var elapsedTime = $('#elasped-time');
var ctx = canvas.getContext('2d');
var CANVAS_HEIGHT = canvas.height;
var CANVAS_WIDTH = canvas.width;
frames = []; // clear existing frames;
startTime = Date.now();
toggleActivateRecordButton();
$('#stop-me').disabled = false;
function drawVideoFrame_(time) {
rafId = requestAnimationFrame(drawVideoFrame_);
ctx.drawImage(video, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
document.title = 'Recording...' + Math.round((Date.now() - startTime) / 1000) + 's';
var url = canvas.toDataURL('image/webp', 1);
frames.push(url);
};
rafId = requestAnimationFrame(drawVideoFrame_);
startRecording();
};
function stop() {
cancelAnimationFrame(rafId);
endTime = Date.now();
$('#stop-me').disabled = true;
document.title = ORIGINAL_DOC_TITLE;
toggleActivateRecordButton();
embedVideoPreview();
};
function embedVideoPreview(opt_url) {
var url = opt_url || null;
var video = $('#video-preview video') || null;
var downloadLink = $('#video-preview a[download]') || null;
if (!video) {
video = document.createElement('video');
video.autoplay = true;
video.controls = true;
video.style.width = canvas.width + 'px';
video.style.height = canvas.height + 'px';
$('#video-preview').appendChild(video);
downloadLink = document.createElement('a');
downloadLink.download = 'capture.webm';
downloadLink.textContent = '[ download video ]';
downloadLink.title = 'Download your .webm video';
var p = document.createElement('p');
p.appendChild(downloadLink);
$('#video-preview').appendChild(p);
} else {
window.URL.revokeObjectURL(video.src);
}
if (!url) {
webmBlob = Whammy.fromImageArray(frames, 1000 / 60);
url = window.URL.createObjectURL(webmBlob);
video.src = url;
downloadLink.href = url;
}
function initEvents() {
$('#camera-me').addEventListener('click', turnOnCamera);
$('#record-me').addEventListener('click', record);
$('#stop-me').addEventListener('click', stop);
}
initEvents();
exports.$ = $;
})(window);
When i am clicking on the download link it is downloaded to the user browser. But i want to send the data to server and save it in the server disk. I have tried to pass the webmblob data to the controller and retrieve. But it is not accessing. I have written code like
$.ajax({
url: '/Home/VideoData',
type: 'POST',
dataType: 'blob',
cache: false,
data: {
data: webmblob
},
contentType: "application/json; charset=utf-8",
error: function (xhr, status, error) {
},
success: function () {
},
});
In the controller i have defined like
public ActionResult VideoData(string data)
{
return Json("success", JsonRequestBehavior.AllowGet);
}
But the data coming to the controller like [object blob].
Sorry for my English. Hope you understand my question. How can i convert it to the video. Any help is surely appreciated.
The Media Recorder API is now supported by both Chrome (49+) and Firefox (30+) and it relies on getUserMedia() to access the webcam.
The video data is stored locally in a JavaScript video/webm Blob object and can be:
played back in a <video> element
downloaded to the client computer as a .webm file
uploaded (POSTed) to a webserver for storage and conversion
This article covers the spec in detail and here's a live demo + GitHub project.
Spec is avb. at w3c
MediaStreamRecorder is a WebRTC API for recording getUserMedia() streams . It allows web apps to create a file from a live audio/video session.
<video autoplay></video>
<script language="javascript" type="text/javascript">
function onVideoFail(e) {
console.log('webcam fail!', e);
};
function hasGetUserMedia() {
// Note: Opera is unprefixed.
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
if (hasGetUserMedia()) {
// Good to go!
} else {
alert('getUserMedia() is not supported in your browser');
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var video = document.querySelector('video');
var streamRecorder;
var webcamstream;
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true, video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
webcamstream = stream;
// streamrecorder = webcamstream.record();
}, onVideoFail);
} else {
alert ('failed');
}
function startRecording() {
streamRecorder = webcamstream.record();
setTimeout(stopRecording, 10000);
}
function stopRecording() {
streamRecorder.getRecordedData(postVideoToServer);
}
function postVideoToServer(videoblob) {
var data = {};
data.video = videoblob;
data.metadata = 'test metadata';
data.action = "upload_video";
jQuery.post("http://www.foundthru.co.uk/uploadvideo.php", data, onUploadSuccess);
}
function onUploadSuccess() {
alert ('video uploaded');
}
</script>
<div id="webcamcontrols">
<button class="recordbutton" onclick="startRecording();">RECORD</button>
</div>
Spec:
http://www.w3.org/TR/mediastream-recording/
you can get recorder media file, send it to the server.
Related
I have developed a test module for generating excel file from json format.
const bodyParser = require('body-parser');
const json2xls = require("json2xls");
const fs = require('fs/promises');
const app = express();
app.use(json2xls.middleware);
app.use(bodyParser.json())
app.post("/", (req, res) => {
if(req.query.token !== "----") res.send(JSON.stringify({isError: true, inf: "Token not valide!"}));
console.log(req.body.DataList);
var xlsq = json2xls(req.body.DataList);
fs.writeFile('data.xlsx', xlsq, 'binary');
res.xls(req.query.name + new Date().toLocaleDateString() + ".xlsx", req.body.data);
})
app.listen(4589, () => console.log("start"));
Next, I send json from the main application to get the converted excel file.
Part from controller С#
public async Task<FileContentResult> GetExcelFile([FromBody] List<GoodsModel> dataList)
{
SideServices sideServices = new(Db, Logger);
List<object> responseDataList = new List<object> { };
object fields = new { codeElem = "Код элемента", shortName = "Наименование", unit = "система измерения", baseNds = "НДС",
sellPrice = "Цена штю", unitWeight = "вес", sumUtd = "Всего, руб", priceUtd = "Цена парйс УТД", baseSale = "Базовая скидка",
remainder = "Cвободный остаток", priceEutd = "Цена eUTD", sumEutd = "Сумма eUTD"};
foreach (GoodsModel item in dataList)
{
responseDataList.Add(new {
codeElem = item.CodeElem,
shortName = item.ShortName,
unit = item.Unit,
baseNds = item.BaseNds,
sellPrice = item.SellPrice,
unitWeight = item.UnitWeight,
sumUtd = item.Sum,
priceUtd = item.PriceUtd,
baseSale = item.BaseSale,
remainder = item.Remainder,
priceEutd = item.PriceEutd,
sumEutd = item.SumEutd
});
}
ExcelImportModel importModel = new ExcelImportModel {
Fields = fields,
Styles = new { },
NameFile = $"Счёт на оплату oт " + SideServices.CurrentDate.ToString(),
DataList = responseDataList.ToArray()
};
Tuple<bool, string, byte[]> resultImport = await sideServices.ToExcelAsync(importModel);
if (resultImport.Item1 == false)
{
string contentType = "application/vnd.ms-excel";
string nameFile = $"Счёт на оплату oт " + SideServices.CurrentDate.ToString();
return File(resultImport.Item3, contentType, nameFile);
}
else
{
return File(new byte[] {1,2,3 }, string.Empty);
}
}
Next method ToExcelAsync():
internal async Task<Tuple<bool, string, byte[]>> ToExcelAsync(ExcelImportModel excelImport)
{
if (excelImport.DataList.Length == 0) return Tuple.Create(true, "Length data is null", new byte[] { 1, 2, 3 });
FileSettings fileSettings = new();
string settingString = await fileSettings.ReadSwitchAsync(TypeDo.settings);
SettingsModel settings = JsonSerializer.Deserialize<SettingsModel>(settingString);
RestClient restClient = new("http://127.0.0.1:4589?" + "token=" + settings.SiteSetModel.APITOKEN);
RestRequest restRequest = new(Method.POST);
restRequest.AddJsonBody(excelImport, "application/json");
IRestResponse response = await restClient.ExecuteAsync(restRequest);
if (response.StatusCode == HttpStatusCode.OK)
{
return Tuple.Create(false, string.Empty, Encoding.UTF8.GetBytes(response.Content));
}
else return Tuple.Create(true, response.ErrorMessage, new byte[] { 1, 2, 3 });
}
Further, on the client side, I get an array of bytes of the generated file.
export default function ExcelConvert(){
const [dataConvert, setDataConvert] = useState([]);
const [errorModal, setErrorModal] = useState({isVisible: false, errorText: ""});
const [appendData, setAppendData] = useState({url: ""});
const ref = useRef(null);
const selector = useSelector(state => state.mainElements);
useEffect(()=>{
const responseArray = [];
for (let i = 0; i < selector.length; i++) {
const element = selector[i];
const newObj = {
codeElem: element.codeElem,
shortName: element.shortName,
countUnit: element.countUnit,
baseUnit: element.baseUnit,
weight: element.unitWeight,
sellPrice: element.sellPrice,
priceUtd: element.sellPrice,
sumUtd: element.sumPrice,
priceEutd: element.priceEUTD,
sumEutd: element.sumEUTD,
baseSale: element.discountItem,
remainder: element.amountUnits
}
responseArray.push(newObj);
}
setDataConvert(responseArray)
}, [selector]);
const handlerClick = () => {
if(dataConvert.length <= 0) return undefined;
const userToken = sessionStorage.getItem("t");
fetch(`${baseurl}/connect/account/excel`, {
method: "POST",
headers: {"Authorization": `Bearer ${userToken}`, "Content-Type": "application/json"},
body: JSON.stringify(dataConvert)
}).then((response) => {
const status = response.status;
if(status === 200) return response.blob();
if(status === 401) deleteAuthData();
if(status >= 400 && status !== 401) setErrorModal({isVisible: true, errorText: "Невозможно загрузить файл!"})
}).then((result) => {
setAppendData({url: window.URL.createObjectURL([result])});
}).catch(e => setErrorModal({isVisible: true, errorText: e}));
}
return <>
<button onClick={handlerClick}>скачать Excel</button>
{appendData.url ? <a style={{display: "block"}} download={"qw.xlsx"} ref={ref} href={appendData.url}>test</a> : <></>}
</>
}
In the first visualization of the code, I added a function that saves the generated excel file;
This file is valid and opens normally.
But the file that I upload on the client side, the file does not open and indicates that the file is not valid and has the wrong format.
Help me solve this problem, what am I doing wrong?
In my current project using ASP.Net vs AngularJs. Now I have a problem about time response of the server.
When load page I send 2 requests ajax to get data.
If I send at the same time function getTopicInfo() and getAnswerList()
$scope.init = function (categoryId, topicId, answerId, commentId, userId) {
$scope.categoryId = categoryId;
$scope.topicId = topicId;
$scope.answerId = answerId;
$scope.commentId = commentId;
$scope.userId = userId;
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
$scope.orderBy = getTopicOrderBy();
getTopicInfo();
getAnswerList();
}
Time response is slowly.
If I call function getAnswerList() after 200ms
$scope.init = function (categoryId, topicId, answerId, commentId, userId) {
$scope.categoryId = categoryId;
$scope.topicId = topicId;
$scope.answerId = answerId;
$scope.commentId = commentId;
$scope.userId = userId;
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
$scope.orderBy = getTopicOrderBy();
getTopicInfo();
setTimeout(function () {
getAnswerList()
}, 200);
}
Time response is quick
I really don't understand. I spend a lot of time on this.
Code of function getTopicInfo() and getAnswerList()
function getTopicInfo() {
var data = {};
data.CategoryId = $scope.categoryId;
data.TopicId = $scope.topicId;
$.ajax({
type: "POST",
url: link("/Topic/GetInfo"),
data: data,
success: function (data) {
$scope.topicInfo = data.Data.TopicInfo;
$scope.load += 1;
$scope.$apply();
addListener();
}
});
}
function getAnswerList(page, scroll) {
page = page || 0;
scroll = scroll != false ? true : false;
var data = {};
data.CategoryId = $scope.categoryId;
data.TopicId = $scope.topicId;
if (page == 0) {
data.CurrentPage = $scope.currentPage;
data.AnswerId = $scope.answerId;
data.CommentId = $scope.commentId;
} else {
data.CurrentPage = page;
data.AnswerId = 0;
data.CommentId = 0;
}
data.ItemsPerPage = $scope.itemsPerPage;
data.OrderBy = $scope.orderBy;
$.ajax({
type: "POST",
url: link("/Answer/GetList"),
data: data,
success: function (data) {
$scope.answerList = data.Data.AnswerList;
$scope.currentPage = data.Data.CurrentPage;
$scope.totalItems = data.Data.TotalItems;
$scope.load += 1;
$scope.$apply();
if (page == 0 && $scope.answerId != 0) {
setTimeout(function () {
scrollToId("answer" + $scope.answerId);
if ($scope.commentId != 0) {
var commentId = $scope.commentId;
if (!$("#comment" + commentId).isInViewport()) {
scrollToId("comment" + commentId);
}
$("#comment" + commentId).css("background-color", "orange")
$("#comment" + commentId).animate({ 'backgroundColor': 'rgba(0, 0, 0, 0)' }, 1000);
}
}, 10);
}
if (page != 0 && scroll) {
scrollToId("answers-header");
}
addListener();
}
});
}
I know that rolling your own HTTP caching is probably ill-advised, but this is what is being used on a project. It appears to have cached a response that is odd, see below, as this request was for an image. It appears to have been a non-error response (otherwise it would not have been cached), however it was not the image, it was an HTML page.. What response codes could be interpreted as success by unity, other than 200?
IEnumerator ReallyDownloadFile(string url, string filename, System.Action<string> on_complete,System.Action<string> on_error, bool allow_caching)
{
WWW www = new WWW (url);
yield return www;
if ((www.error != "")&&(www.error != null)) {
on_error.Invoke (www.error);
} else {
System.IO.File.WriteAllBytes (Application.persistentDataPath + "/filecache/" + filename, www.bytes);
on_complete.Invoke (Application.persistentDataPath + "/filecache/" + filename);
}
}
This is the response. I have no idea where this came from. Router? CDN possibly. Can you explain what happened?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="csrf_token" content="2qe6UtbjdrA6e4ol/eNeo5988K4uoH7r"/>
<meta name="csrf_token" content="UHQ2/wbKRgNdaE14EMIHbKUsa2bLJurm"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv='Pragma' content='no-cache'/>
<script type="text/javascript">
/*
JQuery is not compatible with PSP & NDSi
script execution will stop when the jquery import.
we should put the following script before the jquery is imported
*/
var hardwarePlatform = navigator.platform.toLowerCase();
var agent = navigator.userAgent.toLowerCase();
var isPsp = (agent.indexOf("playstation") != -1);
var isNdsi = (agent.indexOf("nintendo dsi") != -1);
if (isPsp || isNdsi) {
window.location.href = "notsupported.html";
}
</script>
<script type="text/javascript" src="../lib/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../lib/log4javascript_lite.js"></script>
<script type="text/javascript" src="../js/redirect.js"></script>
<title></title>
<script type="text/javascript">
var DEFAULT_GATEWAY_IP = "192.168.1.1";
var DEFAULT_GATEWAY_DOMAIN = new Array();
var GATEWAY_DOMAIN = new Array();
var AJAX_HEADER = '../';
var AJAX_TAIL = '';
var AJAX_TIMEOUT = 30000;
var MACRO_NO_SIM_CARD = '255';
var MACRO_CPIN_FAIL = '256';
var MACRO_PIN_READY = '257';
var MACRO_PIN_DISABLE = '258';
var MACRO_PIN_VALIDATE = '259';
var MACRO_PIN_REQUIRED = '260';
var MACRO_PUK_REQUIRED = '261';
var log = log4javascript.getNullLogger();
var hardwarePlatform = navigator.platform.toLowerCase();
var agent = navigator.userAgent.toLowerCase();
var isIpod = hardwarePlatform.indexOf("ipod") != -1;
var isIphone = hardwarePlatform.indexOf("iphone") != -1;
var isIpad = hardwarePlatform.indexOf("ipad") != -1;
var isAndroid = agent.indexOf("android") !=-1;
log.debug("INDEX : hardwarePlatform = " + hardwarePlatform);
log.debug("INDEX : agent = " + agent);
function gotoPageWithoutHistory(url) {
log.debug('MAIN : gotoPageWithoutHistory(' + url + ')');
window.location.replace(url);
}
// internal use only
function _recursiveXml2Object($xml) {
if ($xml.children().size() > 0) {
var _obj = {};
$xml.children().each(function() {
var _childObj = ($(this).children().size() > 0) ? _recursiveXml2Object($(this)) : $(this).text();
if ($(this).siblings().size() > 0 && $(this).siblings().get(0).tagName == this.tagName) {
if (_obj[this.tagName] == null) {
_obj[this.tagName] = [];
}
_obj[this.tagName].push(_childObj);
}
else {
_obj[this.tagName] = _childObj;
}
});
return _obj;
}
else {
return $xml.text();
}
}
// convert XML string to an Object.
// $xml, which is an jQuery xml object.
function xml2object($xml) {
var obj = new Object();
if ($xml.find('response').size() > 0) {
var _response = _recursiveXml2Object($xml.find('response'));
obj.type = 'response';
obj.response = _response;
}
else if ($xml.find('error').size() > 0) {
var _code = $xml.find('code').text();
var _message = $xml.find('message').text();
log.warn('MAIN : error code = ' + _code);
log.warn('MAIN : error msg = ' + _message);
obj.type = 'error';
obj.error = {
code: _code,
message: _message
};
}
else if ($xml.find('config').size() > 0) {
var _config = _recursiveXml2Object($xml.find('config'));
obj.type = 'config';
obj.config = _config;
}
else {
obj.type = 'unknown';
}
return obj;
}
function getAjaxData(urlstr, callback_func, options) {
var myurl = AJAX_HEADER + urlstr + AJAX_TAIL;
var isAsync = true;
var nTimeout = AJAX_TIMEOUT;
var errorCallback = null;
if (options) {
if (options.sync) {
isAsync = (options.sync == true) ? false : true;
}
if (options.timeout) {
nTimeout = parseInt(options.timeout, 10);
if (isNaN(nTimeout)) {
nTimeout = AJAX_TIMEOUT;
}
}
errorCallback = options.errorCB;
}
var headers = {};
headers['__RequestVerificationToken'] = g_requestVerificationToken;
$.ajax({
async: isAsync,
headers: headers,
//cache: false,
type: 'GET',
timeout: nTimeout,
url: myurl,
//dataType: ($.browser.msie) ? "text" : "xml",
error: function(XMLHttpRequest, textStatus) {
try {
if (jQuery.isFunction(errorCallback)) {
errorCallback(XMLHttpRequest, textStatus);
}
log.error('MAIN : getAjaxData(' + myurl + ') error.');
log.error('MAIN : XMLHttpRequest.readyState = ' + XMLHttpRequest.readyState);
log.error('MAIN : XMLHttpRequest.status = ' + XMLHttpRequest.status);
log.error('MAIN : textStatus ' + textStatus);
}
catch (exception) {
log.error(exception);
}
},
success: function(data) {
log.debug('MAIN : getAjaxData(' + myurl + ') sucess.');
log.trace(data);
var xml;
if (typeof data == 'string' || typeof data == 'number') {
if (-1 != this.url.indexOf('/api/sdcard/sdcard')) {
data = sdResolveCannotParseChar(data);
}
if (!window.ActiveXObject) {
var parser = new DOMParser();
xml = parser.parseFromString(data, 'text/xml');
}
else {
//IE
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.loadXML(data);
}
}
else {
xml = data;
}
if (typeof callback_func == 'function') {
callback_func($(xml));
}
else {
log.error('callback_func is undefined or not a function');
}
}
});
}
function getConfigData(urlstr, callback_func, options) {
var myurl = '../' + urlstr + '';
//var myurl = urlstr + "";
var isAsync = true;
var nTimeout = AJAX_TIMEOUT;
var errorCallback = null;
if (options) {
if (options.sync) {
isAsync = (options.sync == true) ? false : true;
}
if (options.timeout) {
nTimeout = parseInt(options.timeout, 10);
if (isNaN(nTimeout)) {
nTimeout = AJAX_TIMEOUT;
}
}
errorCallback = options.errorCB;
}
$.ajax({
async: isAsync,
//cache: false,
type: 'GET',
timeout: nTimeout,
url: myurl,
//dataType: ($.browser.msie) ? "text" : "xml",
error: function(XMLHttpRequest, textStatus, errorThrown) {
try {
log.debug('MAIN : getConfigData(' + myurl + ') error.');
log.error('MAIN : XMLHttpRequest.readyState = ' + XMLHttpRequest.readyState);
log.error('MAIN : XMLHttpRequest.status = ' + XMLHttpRequest.status);
log.error('MAIN : textStatus ' + textStatus);
if (jQuery.isFunction(errorCallback)) {
errorCallback(XMLHttpRequest, textStatus);
}
}
catch (exception) {
log.error(exception);
}
},
success: function(data) {
log.debug('MAIN : getConfigData(' + myurl + ') success.');
log.trace(data);
var xml;
if (typeof data == 'string' || typeof data == 'number') {
if (!window.ActiveXObject) {
var parser = new DOMParser();
xml = parser.parseFromString(data, 'text/xml');
}
else {
//IE
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.loadXML(data);
}
}
else {
xml = data;
}
if (typeof callback_func == 'function') {
callback_func($(xml));
}
else {
log.error('callback_func is undefined or not a function');
}
}
});
}
function getDomain(){
getConfigData("config/lan/config.xml", function($xml){
var ret = xml2object($xml);
if(ret.type == "config")
{
DEFAULT_GATEWAY_DOMAIN.push(ret.config.landns.hgwurl.toLowerCase());
if( typeof(ret.config.landns.mcdomain) != 'undefined' )
{
GATEWAY_DOMAIN.push(ret.config.landns.mcdomain.toLowerCase());
}
}
}, {
sync: true
});
}
function getQueryStringByName(item) {
var svalue = location.search.match(new RegExp('[\?\&]' + item + '=([^\&]*)(\&?)', 'i'));
return svalue ? svalue[1] : svalue;
}
function isHandheldBrowser() {
var bRet = false;
if(0 == login_status){
return bRet;
}
if (isIphone || isIpod) {
log.debug("INDEX : current browser is iphone or ipod.");
bRet = true;
}
else if (isPsp) {
log.debug("INDEX : current browser is psp.");
bRet = true;
}
else if (isIpad) {
log.debug("INDEX : current browser is ipad.");
bRet = true;
}
else if (isAndroid) {
log.debug("INDEX : current browser is android.");
bRet = true;
}
else {
log.debug("INDEX : screen.height = " + screen.height);
log.debug("INDEX : screen.width = " + screen.width);
if (screen.height <= 320 || screen.width <= 320) {
bRet = true;
log.debug("INDEX : current browser screen size is small.");
}
}
log.debug("INDEX : isHandheldBrowser = " + bRet);
return bRet;
}
function update_openNewWindow () {
if (window.location.href.indexOf('?updataredirect=') > -1) {
var tmpUrl = window.location.href.substring(window.location.href.indexOf("?updataredirect="));
var newUrl = "http://" + tmpUrl.substring(tmpUrl.indexOf("?updataredirect=") + 16) + '/';
document.getElementById("update_newPage").setAttribute("href", newUrl);
document.getElementById("update_newPage").setAttribute("target", "_blank");
if($.browser.msie) {
$("#update_newPage").get(0).click();
} else {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
document.getElementById('update_newPage').dispatchEvent(evt);
}
}
}
var g_requestVerificationToken = '';
function getAjaxToken() {
getAjaxData('api/webserver/token', function($xml) {
var ret = xml2object($xml);
if ('response' == ret.type) {
g_requestVerificationToken = ret.response.token;
}
}, {
sync: true
});
}
getAjaxToken();
var WangatewayAddr="";
var gatewayAddr = "";
var conntection_status = null;
var service_status = null;
var login_status = null;
// get current settings gateway address
getAjaxData("api/dhcp/settings", function($xml) {
var ret = xml2object($xml);
if ("response" == ret.type) {
gatewayAddr = ret.response.DhcpIPAddress;
}
}, {
sync : true
}
);
// get connection status
getAjaxData("api/monitoring/status", function($xml) {
var ret = xml2object($xml);
if ("response" == ret.type) {
conntection_status = parseInt(ret.response.ConnectionStatus,10);
service_status = parseInt(ret.response.ServiceStatus,10);
WangatewayAddr = ret.response.WanIPAddress;
}
}, {
sync : true
}
);
// get connection status
getAjaxData('config/global/config.xml', function($xml) {
var config_ret = xml2object($xml);
login_status = config_ret.config.login;
}, {
sync : true
}
);
if ("" == gatewayAddr) {
gatewayAddr = DEFAULT_GATEWAY_IP;
}
var href = "http://" + DEFAULT_GATEWAY_IP;
try {
href = window.location.href;
}
catch(exception) {
href = "http://" + DEFAULT_GATEWAY_IP;
}
// get incoming url from querystring
var incoming_url = href.substring(href.indexOf("?url=") + 5);
// truncate http://
if (incoming_url.indexOf("//") > -1) {
incoming_url = incoming_url.substring(incoming_url.indexOf("//") + 2);
}
//get *.html
var incoming_html = "";
if (incoming_url.indexOf(".html") > -1) {
incoming_html = incoming_url.substring(incoming_url.lastIndexOf("/") + 1, incoming_url.length);
}
// truncate tail
if (incoming_url.indexOf("/") != -1) {
incoming_url = incoming_url.substring(0, incoming_url.indexOf("/"));
}
incoming_url = incoming_url.toLowerCase();
var bIsSmallPage = isHandheldBrowser();
// var prefix = "http://" + gatewayAddr;
var g_indexIncomingUrlIsGateway = false;
// if incoming url == 192.168.1.1 or MobileWifi.home then goto login
// page
window.name = getQueryStringByName("version");
//check login status
var LOGIN_STATES_SUCCEED = "0";
var userLoginState = LOGIN_STATES_SUCCEED;
getAjaxData('api/user/state-login', function($xml) {
var ret = xml2object($xml);
if (ret.type == 'response') {
userLoginState=ret.response.State;
}
}, {
sync: true
});
$(document).ready(function() {
update_openNewWindow();
if(true == bIsSmallPage) {
if (userLoginState != LOGIN_STATES_SUCCEED) {
getAjaxData('config/global/config.xml', function($xml) {
var config_ret = xml2object($xml);
if(config_ret.type == 'config') {
if(config_ret.config.commend_enable == '1') {
gotoPageWithoutHistory("../html/commend.html");
g_indexIncomingUrlIsGateway = true;
}else {
g_indexIncomingUrlIsGateway = redirectOnCondition("",'index');
}
}
},{
sync: true
});
} else {
g_indexIncomingUrlIsGateway = redirectOnCondition("",'index');
}
} else {
g_indexIncomingUrlIsGateway = redirectOnCondition("",'index');
}
$( function() {
getDomain();
if (g_indexIncomingUrlIsGateway) {
return;
}
else if (conntection_status == 901 && service_status == 2) {
if ((incoming_url.indexOf(gatewayAddr)==0)
|| (incoming_url.indexOf(DEFAULT_GATEWAY_DOMAIN)==0)
|| (incoming_url.indexOf(WangatewayAddr)==0)
|| (incoming_url.indexOf(GATEWAY_DOMAIN)==0)){
gotoPageWithoutHistory("home.html");
}
else {
gotoPageWithoutHistory("update.html");
}
}
else {
gotoPageWithoutHistory("home.html");
}
});
});
</script>
</head>
<body style="background-color: #FFFFFF;">
<div>
<a id="update_newPage" href="#" target="_blank"></a>
</div>
<noscript>
Sorry, your browser does not support javascript.
</noscript>
</body>
</html>
This looks like a DNS intercept/attempted redirect by a router. It looks like a situation where a 200 is returned with content that is not what was requested. The question now becomes "How can this type of situation be detected?"
One approach would be to use http://clients1.google.com/generate_204 to tell whether you are behind a captive portal or not: since a 204 would be unlikely to be used by the router in this situation. However this seems like a flawed approach for this use case.
Perhaps this question would be a good example of why one should not roll one's own cache?
Anyway is this necessary at all? I'm starting to think HTTP caching in Unity may just work without this...
In my _Layout.cshtml page there is a textbox that allows user to type his/her email address(this is for newsletter).if typed email address exists it does not insert to the database and if not it insert to the database. at the same time if not inserted I want to show an error message and if insert I want to show success message.this is how I insert to the database,
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//want to send success text
}
else
{
//want to send error text
}
return Json(new { });
}
if success or error it returns to the same _Layout.csthml page.
how can I do that.hope your help.
You can use. return content.
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//return Content("Your information saved successfully");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
else
{
//return Content("Already exist. Please choose another.");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success";
}
else
{
myMessage="failed";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In your view.
$.post('#Url.Action("getNewsLetterMail", "yourControllerName")', { N_id: N_id, N_EmailAdd: N_EmailAdd }).done(function (data) {
if (data == "success") {
alert("Success!");
}
if( data== "failed") {
alert("Failed!");
}
}
I have no experience but I would try something like that:
in my viewmodel I would put
string info
then in my razor view
#Html.DisplayFor(m=>m.info)
and in controller
if(existing){info="success"}
You would have to pass info to the viewmodel in your controller
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success!";
}
else
{
myMessage="Failed!";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In Views, you can add jquery to display the message. Following is an example to retrieve the message in Views. You can edit the names in your form accordingly.
`<script type="text/javascript">
$(document).ready(function () {
$("#yourForm").submit(function (e) {
e.preventDefault();
var valid = $("#yourForm").valid();
if (valid) {
$.ajax({
url: "/getNewsLetterMail",
type: "POST",
data: {
Name: $("#N_id").val(),
Email: $("#N_EmailAdd").val(),
},
success: function (data) {
alert(data);
reset();
}
});
}
});
});
</script>'
I am using the below code to view the uploaded file using javascript. It display the fake path so i can't able to upload the files to server path. please help me to upload the images to server.mappath folder.
<input type='file' name='file' id='file' value='Choose Photo' accept='image/png,image/jpeg' onchange='handleFileSelect(this);' />
<script type="text/javascript">
function handleFileSelect(input) {
try {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('hf_image').value = e.target.result
$('#preview').attr('src', document.getElementById('hf_image').value);
}
reader.readAsDataURL(input.files[0]);
}
}
catch (ex) {
alert('Image Preview : ' + ex.Message);
}
}
</script>
var attachments={};
function imageSelected(myFiles){
for (var i = 0, f; f = myFiles[i]; i++) {
var imageReader = new FileReader();
imageReader.onload = (function(aFile){
return function(e){
var tempFileData=e.target.result;
attachments[aFile.name]={};
attachments[aFile.name]["content_type"]=tempFileData.split(",")[0].split(":")[1].split(";")[0];
attachments[aFile.name]["data"]=tempFileData.split(",")[1];
};
})(f);
imageReader.readAsDataURL(f);
}
}
<input type='file' onchange="imageSelected(this.files)">
the above code may be helpful for you
attachments json holds the file details
Why you don't use AjaxFileUploader, that is easy to use
Follow this steps to approach your target,
Step 1:
dRAG Jquery files to Head tag.
add this code to a JavaScript file and dragged it into the head of your page.
jQuery.extend({
createUploadIframe: function (id, uri) {
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if (window.ActiveXObject) {
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function (id, fileElementId, data) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if (data) {
for (var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++) {
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {}
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function (isTimeout) {
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status);
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && ! --jQuery.active)
jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function () {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
jQuery(form).attr('encoding', 'multipart/form-data');
}
else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback);
return { abort: function () { } };
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
return data;
}
})
something like this:
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="Scripts/fileUploader.js" type="text/javascript"></script>
Step 2:
Add this tags into body page.
<input id="fileToUpload" type="file" size="45" name="fileToUpload" />
<button id="btnUploadNewLicense" onclick="return ajaxFileUpload('New');">
Upload</button><br />
<div id="loading" style="display: none;">
Please wait...</div>
Step 3:
Add a generic handler file named "FileUpload.ashx" into the your project root,
add this following code into "FileUplod.ashx"
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string action = request["Action"];
switch (action)
{
case "New":
string result = "failed";
try
{
string fileName = SaveCaper(context);
result = "successed";
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
catch
{
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
break;
default:
throw new Exception("Invalid sort column name!.");
}
}
private string SaveCaper(HttpContext context)
{
string fileName = string.Empty;
string path = context.Server.MapPath("~/NewImages");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
try
{
var file = context.Request.Files[0];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
try
{
file.SaveAs(fileName);
}
catch (Exception exp)
{
//log the exception
}
}
catch (Exception exp)
{
//log the exception
}
return fileName;
}
public bool IsReusable
{
get
{
return false;
}
}
also you need to add System.IO in top of the handler code behind.
Step 4:
Add this script to your head after your JS files prototype
<script language="javascript" type="text/javascript">
$(document).ready(function () {
function ajaxFileUpload(mode) {
var fupl = 'fileToUpload';
var fileName = $('#fileToUpload').val();
if (fileName == "" || fileName == null)//if user doesn't select an image
{
$("#loading").html("");
$("#loading").append("<br/><b>Please select an image...</b>");
}
else {
var vars = fileName.split("."); //get file extension.
if (vars[1].toString().toLowerCase() != "jpg") {//check the file extension.
$("#loading").html("");
$("#loading").append("<br/>The image format is not valid !.");
return false;
}
$("#loading").ajaxStart(function () { $('#dialogUpdateLicense :input').attr('disabled', true); $(this).show(); })
.ajaxComplete(function () { $('#dialogUpdateLicense :input').removeAttr('disabled'); });
$("#loading").html("");
$("#loading").append("<br/><b>Please wait...</b>");
$.ajaxFileUpload
({
url: 'FileHandler.ashx',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
data: { Action: mode },
success: function (data) {
if (data.result == "successed")
$("#loading").html("The image uploaded successfully!.");
},
error: function (data, e) {
$("#loading").html("An error occured!.");
}
})
}
return false;
}
</script>
All thing was tested and works properly for me
I hope it will help you.