I am trying to insert multiple images in a single row in a field in oracle database, please suggest how to achieve it. Below are the details
image is rendering on the browser and I want to store multiple image through it in oracle db. Each image will have an id generating dynamically
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
Find the bellow HTML code
<h2>preview multiple images before upload using jQuery</h2>
<input type="file" id="files" name="files[]" multiple />
<asp:Button ID="Button3" runat="server" BorderColor="#CCFF66"
ForeColor="#0066FF" Text="Insert Data" />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = 0;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
if (filesLength == 1) {
a = a + 1;
}
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
Id: "img"+ a.toString(),
src: e.target.result,
title: file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
</body>
</html>
for saving image into oracle db I am using ajax and created webservice to push data into db:
[WebMethod]
public static void SaveUser(User user)
{
String connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO par_cinfo(Product_Id,IMAGETYPE ) VALUES (:IMAGETYPE )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("IMAGETYPE ", user.IMAGETYPE);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
public class User
{
public decimal Product_Id { get; set; }
public Image IMAGETYPE { get; set; }
}
jQuery ajax on button click to send data to webservices:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=Button3]").bind("click", function () {
var user = {};
user.Product_Id = 1;
user.IMAGETYPE= "here dynamic image id which is uploaded should be present "
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
//data: JSON.stringify({user:user}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
The table which I created in oracle is as follows simply for entering the data in the table:
Create table par_cinfo
(
Product_Id NUMBER(10) NOT NULL PRIMARY KEY,
IMAGETYPE BLOB
)
I have strange problem with jQuery AJAX and ASHX behavior. Here is my code:
<input type="file" ID="FileUpload1" multiple="multiple" />
<input type="button" ID="Button1" Text="Upload Selected File(s)" />
function Upload() {
var data = new FormData();
jQuery.each($('#FileUpload1')[0].files, function (i, file) {
data.append('file-' + i, file);
});
$.ajax({
url: "/basic/fileupload/FileUploadHandler.ashx",
type: "POST",
contentType: false,
processData: false,
cache: false,
async: true,
data: data,
error: function (data) {
alert("Erro no envio de fotos do projecto. " + data.status);
}
});
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/files/") + str_image;
file.SaveAs(pathToSave_100);
}
}
// database record update logic here ()
context.Response.Write(str_image);
}
catch (Exception ac)
{
}
}
Eeverything seems to be fine, but the result is:
context.Request.Files[0]
{System.Web.HttpPostedFile}
ContentLength: -2
ContentType: "image/png"
FileName: "icon-large.png"
InputStream: {System.Web.HttpInputStream}
I can receive file name but the ContentLength is always -2 and after saving the file It's just 0 bytes is size. Could you please help me to solve this problem?
UPDATE :
I've found something new , it's working fine with ASP.net Development Server (Running Application Directly by pushing F5 Key in Visual Studio) but something is wrong with IIS 8.5 configuration
also My web.config request length parameters are :
<httpRuntime requestValidationMode="2.0" maxRequestLength="10240000" requestLengthDiskThreshold="10240000" />
UPDATE 2:
changing Application pool's to Managed pipeline mode to Classic will solve the problem , but I will loose my URL Rewriting, so I can't change my Pipeline Mode. Any Idea?
I've found the solution to solve this problem. I don't know is it fine or not but solved my case :
I used
void Application_BeginRequest(object sender, EventArgs e)
in
global.asax
file to manage request because the contents is visible there correctly.
Any other Idea?
hello everybody I'm new here and I'm new to jquery too
I apply this article to my website to upload multiple data at once
using-dropzone-js-file-image-upload-in-asp-net-webform-c
while I'm using this code when I click on the dropzone area it's uploading the photos directly to ~/work/
so what I hope so is to use a button with id=post
to upload these images in dropzone area only after click on it
so here is my code:
here is the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link href="css/dropzone.css" rel="stylesheet" type="text/css" />
<script src="js/dropzone.js" type="text/javascript"></script>
the html part:
<div id="dZUpload" class="dropzone ">
<div class="dz-default dz-message"></div>
</div>
the javascript part:
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
$("#dZUpload").dropzone({
url: 'FileUploader.ashx',
addRemoveLinks: true,
maxFiles: 3,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
}
});
});
</script>
and finally the Generic Handler "
FileUploader.ashx
:
<%# WebHandler Language="C#" Class="FileUploader" %>
using System;
using System.Web;
using System.IO;
public class FileUploader : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("~/work/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "WorkPhoto_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/work/") + str_image;
file.SaveAs(pathToSave_100);
}
}
context.Response.Write(str_image);
}
public bool IsReusable {
get {
return false;
}
}
}
Here i think this will solve your Problems:
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
var myDropzone = new Dropzone("#dZUpload", {
url: 'FileUploader.ashx', autoProcessQueue: false, addRemoveLinks: true, maxFiles: 3,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
});
$('#button').on('click', function (e) {
myDropzone.processQueue();
});
});
I am working on a web application developed using Asp.Net MVC which on which I have a page on which data gets updated at realtime whenever data is modified on the database. I have some source on line and tried to implement this feature but it resulted in huge invalid data on the webpage.
I am using SQL dependency and SignalR to achieve this as follows
In Global.asax, I have the following
protected void Application_Start()
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
and in Models section I have the following classes
public class JobInfo
{
public int JobID { get; set; }
public string Name { get; set; }
public DateTime LastExecutionDate { get; set; }
public string Status { get; set; }
}
public class JobInfoRepository
{
public IEnumerable<JobInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo(){
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3) }).ToList();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
JobHub.Show();
}
}
I have created a SignalR Hub class as follows which has the Show() function used in the above class
using Microsoft.AspNet.SignalR.Hubs;
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
And I have the controller in which I am calling GetData() method defined in the JobInfoRepository class
public class JobInfoController : Controller
{
// GET: /JobInfo/
JobInfoRepository objRepo = new JobInfoRepository();
public IEnumerable<JobInfo> Get()
{
return objRepo.GetData();
}
}
I have created an Action named JobInfo in HomeController and returned the following view
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div>
<table id="tblJobInfo" class="clientTable" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
#section scripts {
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/App/JobInfo.js"></script>
}
to retrieve the data and supply it to tblJobInfo id in the above html, a java script function is used
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
As in the demo I found it to be working fine but when I go to http://localhost:57044/Home/JobInfo/ I get invalid data on the page besides not getting the realtime notifications as in the following image
reference to the source I found online is http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency
Using html2canvas how can I save a screen shot to an object? I've been exploring the demos, and see that the function to generate the screenshot is generated as follows:
$(window).ready(function() {
('body').html2canvas();
});
What I've tried doing is
$(window).ready(function() {
canvasRecord = $('body').html2canvas();
dataURL = canvasRecord.toDataURL("image/png");
dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
upload(dataURL);
});
And, I then pass it to my upload() function. The problem I am having, is I can't figure out where the screenshot is being made in the html2canvas() library or what function returns it. I've tried converting the canvas object using this answer from SO (though I'm not certain I need to do this).
I just asked a question on how to upload a file to imgur, and the answers there (particularly #bebraw's) help me to understand what I need to do.
The upload() function is from the Imgur example api help:
function upload(file) {
// file is from a <input> tag or from Drag'n Drop
// Is the file an image?
if (!file || !file.type.match(/image.*/)) return;
// It is!
// Let's build a FormData object
var fd = new FormData();
fd.append("image", file); // Append the file
fd.append("key", "mykey"); // Get your own key: http://api.imgur.com/
// Create the XHR (Cross-Domain XHR FTW!!!)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
xhr.onload = function() {
// Big win!
// The URL of the image is:
JSON.parse(xhr.responseText).upload.links.imgur_page;
}
// Ok, I don't handle the errors. An exercice for the reader.
// And now, we send the formdata
xhr.send(fd);
}
I have modified and annotated the method from this answer. It sends only one file, with a given name, composed from a <canvas> element.
if (!('sendAsBinary' in XMLHttpRequest.prototype)) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
/*
* #description Uploads a file via multipart/form-data, via a Canvas elt
* #param url String: Url to post the data
* #param name String: name of form element
* #param fn String: Name of file
* #param canvas HTMLCanvasElement: The canvas element.
* #param type String: Content-Type, eg image/png
***/
function postCanvasToURL(url, name, fn, canvas, type) {
var data = canvas.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var boundary = 'ohaiimaboundary';
xhr.setRequestHeader(
'Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary([
'--' + boundary,
'Content-Disposition: form-data; name="' + name + '"; filename="' + fn + '"',
'Content-Type: ' + type,
'',
atob(data),
'--' + boundary + '--'
].join('\r\n'));
}
This code works for me. It will generate screenshot by html2canvas, upload the screenshot to imgur api, and return the imgur url.
<button class="upload" >Upload to Imgur</button>
<script>
$(".upload").on("click", function(event) {
html2canvas($('body'), {
onrendered: function(canvas) {
document.body.appendChild(canvas);
try {
var img = canvas.toDataURL('image/jpeg', 0.9).split(',')[1];
} catch(e) {
var img = canvas.toDataURL().split(',')[1];
}
// open the popup in the click handler so it will not be blocked
var w = window.open();
w.document.write('Uploading...');
// upload to imgur using jquery/CORS
// https://developer.mozilla.org/En/HTTP_access_control
$.ajax({
url: 'http://api.imgur.com/2/upload.json',
type: 'POST',
data: {
type: 'base64',
// get your key here, quick and fast http://imgur.com/register/api_anon
key: 'your api key',
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: img
},
dataType: 'json'
}).success(function(data) {
w.location.href = data['upload']['links']['imgur_page'];
}).error(function() {
alert('Could not reach api.imgur.com. Sorry :(');
w.close();
});
},
});
});
</script>
//Here I am using html2Canvas to capture screen and Java websockets to transfer data to server
//Limitation:Supported on latest browsers and Tomcat
Step1)Client Side : webSock.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- Arun HTML File -->>
<html>
<head>
<meta charset="utf-8">
<title>Tomcat web socket</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="html2canvas.js?rev032"></script>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8080/WebSocketSample/wsocket");
ws.onopen = function () {
console.log("Web Socket Open");
};
ws.onmessage = function(message) {
console.log("MSG from Server :"+message.data);
//document.getElementById("msgArea").textContent += message.data + "\n";
document.getElementById("msgArea").textContent +" Data Send\n";
};
function postToServerNew(data) {
ws.send(JSON.stringify(data));
document.getElementById("msg").value = "";
}
//Set Interval
setInterval(function(){
var target = $('body');
html2canvas(target, {
onrendered: function(canvas) {
var data = canvas.toDataURL();
var jsonData = {
type: 'video',
data: data,
duration: 5 ,
timestamp: 0, // set in worker
currentFolder: 0,// set in worker
};
postToServerNew(jsonData);
}
});
},9000);
function closeConnect() {
ws.close();
console.log("Web Socket Closed: Bye TC");
}
</script>
</head>
<body>
<div>
<textarea rows="18" cols="150" id="msgArea" readonly></textarea>
</div>
<div>
<input id="msg" type="text"/>
<button type="submit" id="sendButton" onclick="postToServerNew('Arun')">Send MSG</button>
</div>
</body>
</html>
Step2)Server Side
File 1)
package Arun.Work;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
/**
* Need tomcat-koyote.jar on class path, otherwise has compile error
* "the hierarchy of the type ... is inconsistent"
*
* #author Arun
*
*/
public class MyInBound extends MessageInbound {
private String name;
private WsOutbound myoutbound;
private String targetLocation;
public MyInBound(HttpServletRequest httpSerbletRequest, String targetLocation) {
this.targetLocation = targetLocation;
}
#Override
public void onOpen(WsOutbound outbound) {
System.out.println("Web Socket Opened..");
/*this.myoutbound = outbound;
try {
this.myoutbound.writeTextMessage(CharBuffer.wrap("Web Socket Opened.."));
} catch (Exception e) {
throw new RuntimeException(e);
}*/
}
#Override
public void onClose(int status) {
System.out.println("Close client");
// remove from list
}
#Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
System.out.println("onBinaryMessage Data");
try {
writeToFileNIOWay(new File(targetLocation), arg0.toString() + "\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
//this.myoutbound.flush();
}
}// end of onBinaryMessage
#Override
protected void onTextMessage(CharBuffer inChar) throws IOException {
System.out.println("onTextMessage Data");
try {
writeToFileNIOWay(new File(targetLocation), inChar.toString() + "\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
//this.myoutbound.flush();
}
}// end of onTextMessage
public void writeToFileNIOWay(File file, String messageToWrite) throws IOException {
System.out.println("Data Location:"+file+" Size:"+messageToWrite.length());
//synchronized (this){
byte[] messageBytes = messageToWrite.getBytes();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(raf.length());
FileChannel fc = raf.getChannel();
MappedByteBuffer mbf = fc.map(FileChannel.MapMode.READ_WRITE, fc.position(), messageBytes.length);
mbf.put(messageBytes);
fc.close();
//}
}//end of method
/*
* //Working Fine public void writeToFileNIOWay(File file, String
* messageToWrite) throws IOException { byte[] messageBytes =
* messageToWrite.getBytes(Charset.forName("ISO-8859-1")); RandomAccessFile
* raf = new RandomAccessFile(file, "rw"); raf.seek(raf.length());
* FileChannel fc = raf.getChannel(); MappedByteBuffer mbf =
* fc.map(FileChannel.MapMode.READ_WRITE, fc.position(),
* messageBytes.length);
*
* mbf.put(messageBytes); fc.close(); }
*/
}
File 2)
package Arun.Work;
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
/**
* WebSocketServlet is contained in catalina.jar. It also needs servlet-api.jar
* on build path
*
* #author Arun
*
*/
#WebServlet("/wsocket")
public class MyWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
// for new clients, <sessionId, streamInBound>
private static ConcurrentHashMap<String, StreamInbound> clients = new ConcurrentHashMap<String, StreamInbound>();
#Override
protected StreamInbound createWebSocketInbound(String protocol, HttpServletRequest httpServletRequest) {
// Check if exists
HttpSession session = httpServletRequest.getSession();
// find client
StreamInbound client = clients.get(session.getId());
if (null != client) {
return client;
} else {
System.out.println(" session.getId() :"+session.getId());
String targetLocation = "C:/Users/arsingh/Desktop/AnupData/DATA/"+session.getId();
System.out.println(targetLocation);
File fs=new File(targetLocation);
boolean bool=fs.mkdirs();
System.out.println(" Folder created :"+bool);
client = new MyInBound(httpServletRequest,targetLocation+"/Output.txt");
clients.put(session.getId(), client);
}
return client;
}
/*public StreamInbound getClient(String sessionId) {
return clients.get(sessionId);
}
public void addClient(String sessionId, StreamInbound streamInBound) {
clients.put(sessionId, streamInBound);
}*/
}