Websocket send image file by Javascript client - javascript

I'm writing a simple application in which a javascript web socket client has to send image to a webscoket implemented by tomcat and Java language.
when I send a string message every thing is going well but #Onmessage event don't be fired if I send an image data. I've spent 2 days but haven't the solution yet.
Java WebSocket Code:
#ServerEndpoint("/sendfile")
public class BinaryWebSocketServer {
private
static final Set<Session> sessions =
Collections.synchronizedSet(new HashSet<Session>());
#OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("onOpen_File::" + session.getId());
}
#OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("onClose_File::" + session.getId());
}
#OnMessage
public void onMessage(byte[] data, Session session) {
System.out.println("onByteArrayMessage::From=" + session.getId() + " with len:" + data.length );
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2;
try {
bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("image created");
}
#OnError
public void onError(Throwable t) {
System.out.println("onError::" + t.getMessage());
}
}
Javascript Client:
<body>
<h2>File Upload</h2> Select file
<input type="file" id="filename" />
<br>
<input type="button" value="Connect" onclick="connectChatServer()" />
<br>
<input type="button" value="Upload" onclick="sendFile()" />
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
<br />
<textarea id="echoText" rows="5" cols="30"></textarea>
<script>
var webSocket = new WebSocket("ws://192.168.1.55:8081/Hello-Capture/sendfile");
webSocket.binaryType = 'arraybuffer';
webSocket.onopen = function(message){ wsOpen(message);};
//webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wsError(message){
echoText.value += "Error ..." + message.code +" \n";
}
function sendFile() {
var file = document.getElementById('filename').files[0];
var reader = new FileReader();
var rawData = new ArrayBuffer();
reader.loadend = function(e) {
};
reader.onload = function(e) {
var rawData = e.target.result;
var byteArray = new Uint8Array(rawData);
var fileByteArray = [];
webSocket.send(byteArray.buffer);
echoText.value =("the File has been transferred.\n");
};
reader.readAsArrayBuffer(file);
}
</script>
</body>

Finally I find the solution so I comment it maybe some one else gets stuck into.
I've forgotten to pass a boolean parameter to onMessage function.
the correct form is :
#OnMessage
public void onMessage(byte[] data,boolean last, Session session) {
.
.
.
}

Related

Error in getting table row value to be deleted/updated. String input as undefined

I am making a simple CRUD function for a bill management system. It uses Jquery AJAX JSON to communicate to the servlets.
The update and delete functions are activated by buttons in a dynamically generated table with hidden field that contains the 'billID'.
However when tested it gives an error For input String : "undefined". I think the error should be in billid hidden field somehow not been set? But I'm not sure and would like a bit of help.
.jsp HTML table.
<form id="formBill" name="formBill">
UserID : <input id="UserID" name="UserID" type="text" class= "form-control form-control-sm" required> <br>
Billing Date (yyyy-mm-dd): <input id="BillingDate" name="BillingDate" type="text" class= "form-control form-control-sm" required> <br>
Unit Cost : <input id="UnitCost" name="UnitCost" type="text" class="form-control form-control-sm" required> <br>
Units Used : <input id="UnitsUsed" name="UnitsUsed" type="text" class="form-control form-control-sm" required> <br>
Service Charge : <input id="ServiceCharge" name="ServiceCharge" type="text" class="form-control form-control-sm" required> <br>
Bill Settled : <select id="BillSettled" name="BillSettled" required>
<option value="false">False</option>
<option value="true">True</option>
</select>
<br><br><br>
<input id="btnSave" name="btnSave" type="button" value="Save" class="btn btn-primary">
<input type="hidden" id="hidBillIDSave" name="hidBillIDSave" value="">
</form>
<br>
<div id="alertSuccess" class="alert alert-success"></div>
<div id="alertError" class="alert alert-danger"></div>
<br>
<div id="divItemsGrid">
</div>
The dynamically generated table is placed in the divItemsGrid div.
Here are the Jquery ajax code
// Save =================================================
$(document).on("click", "#btnSave", function(event) {
// Clear alerts---------------------
$("#alertSuccess").text("");
$("#alertSuccess").hide();
$("#alertError").text("");
$("#alertError").hide();
// Form validation-------------------
var status = validateBillForm();
if (status != true) {
$("#alertError").text(status);
$("#alertError").show();
return;
}
//var type = ($("#hidItemIDSave").val() == "") ? "POST" : "PUT";
var type;
if ($("#hidBillIDSave").val() == ""){
type = "POST";
}
else{
type = "PUT";
}
$.ajax(
{
url: "BillsAPI",
type: type,
data: $("#formBill").serialize(),
dataType: "text",
error: function(response, status, error) {
console.log(response);
},
complete: function(response, status)
{
onBillSaveComplete(response.responseText, status);
}
});
});
// UPDATE==========================================
$(document).on("click", ".btnUpdate", function(event) {
$("#hidBillIDSave").val($(this).data("billID"));
$("#UserID").val($(this).closest("tr").find('td:eq(0)').text());
$("#BillingDate").val($(this).closest("tr").find('td:eq(1)').text());
$("#UnitCost").val($(this).closest("tr").find('td:eq(2)').text());
$("#UnitsUsed").val($(this).closest("tr").find('td:eq(3)').text());
$("#ServiceCharge").val($(this).closest("tr").find('td:eq(4)').text());
$("#BillSettled").val($(this).closest("tr").find('td:eq(5)').text());
});
// DELETE==============================================
$(document).on("click", ".btnRemove", function(event) {
$.ajax(
{
url: "BillsAPI",
type: "DELETE",
data: "billID=" + $(this).data("billID"),
dataType: "text",
complete: function(response, status) {
onBillDeleteComplete(response.responseText, status);
}
});
});
The update function sets the values into the form. If there is a hidden value then we use PUT to update the table. If not it becomes a POST.
I believe the error is here. Somehow the hidden billID value must not be getting set.
Below are the CRUD functions. They are a bit long but the dynamically generated table is in the read function.
//Create Bills
public String createBill(String BillingDate, String unitCost, String unitsUsed, String serviceCharge, String billSettled, String userID) {
String output = "";
try {
Connection con = connect();
if(con == null) {
return "Error while connecting to the database for inserting.";
}
//calculate total cost
int totalCost = (Integer.parseInt(unitCost) * Integer.parseInt(unitsUsed)) + Integer.parseInt(serviceCharge);
//create a prepared statement
String query = "insert into bills (`billDate`, `unitCost`, `unitsUsed`, `serviceCharge`, `totalCost`, `settled`, `userID`)"
+" values(?,?,?,?,?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
//converting String to util.Date to sql.Date
java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(BillingDate);
java.sql.Date date2 = new java.sql.Date(date1.getTime());
// binding values
preparedStmt.setDate(1, date2);
preparedStmt.setInt(2, Integer.parseInt(unitCost));
preparedStmt.setInt(3, Integer.parseInt(unitsUsed));
preparedStmt.setInt(4, Integer.parseInt(serviceCharge));
preparedStmt.setInt(5, totalCost);
preparedStmt.setBoolean(6, Boolean.parseBoolean(billSettled));
preparedStmt.setInt(7, Integer.parseInt(userID));
// execute the statement
preparedStmt.execute();
con.close();
//output = "Inserted successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while inserting the item.";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
//Update Bills
//for settles bills
public String updateSettledBills(String billID, String billSettled) {
String output = "";
Connection con = connect();
try {
if(con == null) {
return "Error while connecting to the database for updating.";
}
//create prepared statement
String query = "update bills set settled=? where billID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
//binding values
preparedStmt.setBoolean(1, Boolean.parseBoolean(billSettled));
preparedStmt.setInt(2, Integer.parseInt(billID));
//execute statement
preparedStmt.execute();
con.close();
//output = "Updated successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while updating bill";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
//Delete Bills
public String deleteBill(String billID) {
String output = "";
try {
Connection con = connect();
if(con == null) {
return "Error while connecting to the database for deleting.";
}
//create prepared statement
String query = "delete from bills where billID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
// binding values to prepared statement
preparedStmt.setInt(1, Integer.parseInt(billID));
// execute the statement
preparedStmt.execute();
con.close();
//output = "Deleted successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while deleting the bill.";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
Finally, here are the servlets.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String output = billObj.createBill(
request.getParameter("BillingDate"),
request.getParameter("UnitCost"),
request.getParameter("UnitsUsed"),
request.getParameter("ServiceCharge"),
request.getParameter("BillSettled"),
request.getParameter("UserID"));
response.getWriter().write(output);
}
// Convert request parameters to a Map
private static Map getParasMap(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
try {
Scanner scanner = new Scanner(request.getInputStream(), "UTF-8");
String queryString = scanner.hasNext() ? scanner.useDelimiter("\\A").next() : "";
scanner.close();
String[] params = queryString.split("&");
for (String param : params) {
String[] p = param.split("=");
map.put(p[0], p[1]);
}
} catch (Exception e) {
}
return map;
}
/**
* #see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
*/
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paras = getParasMap(request);
//System.out.println(paras.get("billID").toString());
String output = billObj.updateSettledBills(
paras.get("billID").toString(),
paras.get("BillSettled").toString());
response.getWriter().write(output);
}
/**
* #see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
*/
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paras = getParasMap(request);
String output = billObj.deleteBill(paras.get("billID").toString());
response.getWriter().write(output);
}
Sorry for the bloated post. I would greatly appreciate some with regards to this.

How to send an image using websockets in java?

I am trying to send an image by drag and drop in send message area but its failing to do so. I dont know how to send an image in this code. Can someone please help me out?
ChatEndpoint.java
This is serverendpoint of websocket.I have four methods.onOpen,onClose,onMessage and onError.I am not doing anything in onOpen method.This method gets called when websocket establishes the connection.When the websocket tries to send message to the client,onMessage method gets called.Here the message sent from the jsp page(client) sends it in json string format to the server.The object mapper converts it to java object.I have also made an enum for MessageType having two options LOGIN and MESSAGE.I am checking inf the java object matches with the login message type then it stores the name of chat user from properties of user obtained from session object.It also then sends the session object to join method where the session is added to the list of session object.It also send the message the user has joined the chat room.If messagetype is a message then it sends it to send message method of room class where the message is sent back to the client using sendText.
#ServerEndpoint(value = "/chat")
public class ChatEndpoint {
private Logger log = Logger.getLogger(ChatEndpoint.class.getSimpleName());
private Room room = Room.getRoom();
#OnOpen
public void onOpen(final Session session, EndpointConfig config) {}
#OnMessage
public void onMessage(final Session session, final String messageJson) {
ObjectMapper mapper = new ObjectMapper();
ChatMessage chatMessage = null;
try {
chatMessage = mapper.readValue(messageJson, ChatMessage.class);
} catch (IOException e) {
String message = "Badly formatted message";
try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, message));
} catch (IOException ex) { log.severe(ex.getMessage()); }
} ;
Map<String, Object> properties = session.getUserProperties();
if (chatMessage.getMessageType() == MessageType.LOGIN) {
String name = chatMessage.getMessage();
properties.put("name", name);
room.join(session);
room.sendMessage(name + " - Joined the chat room");
}
else {
String name = (String)properties.get("name");
room.sendMessage(name + " - " + chatMessage.getMessage());
}
}
#OnClose
public void OnClose(Session session, CloseReason reason) {
room.leave(session);
room.sendMessage((String)session.getUserProperties().get("name") + " - Left the room");
}
#OnError
public void onError(Session session, Throwable ex) { log.info("Error: " + ex.getMessage()); }
}
Room.java
public class Room {
private static Room instance = null;
private List<Session> sessions = new ArrayList<Session>();
public synchronized void join(Session session) { sessions.add(session); }
public synchronized void leave(Session session) { sessions.remove(session); }
public synchronized void sendMessage(String message) {
for (Session session: sessions) {
if (session.isOpen()) {
try { session.getBasicRemote().sendText(message); }
catch (IOException e) { e.printStackTrace(); }
}
}
}
public synchronized static Room getRoom() {
if (instance == null) { instance = new Room(); }
return instance;
}
}
index.jsp
Here i am sending the wsUri which is stored in context param as ws://localhost:8080/single-room-chat/chat
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<% String WsUrl = getServletContext().getInitParameter("WsUrl"); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name='viewport' content='minimum-scale=1.0, initial-scale=1.0,
width=device-width, maximum-scale=1.0, user-scalable=no'/>
<title>single-room-chat</title>
<link rel="stylesheet" type="text/css" href="content/styles/site.css">
<script type="text/javascript" src="scripts/chatroom.js"></script>
<script type="text/javascript">
var wsUri = '<%=WsUrl%>';
var proxy = CreateProxy(wsUri);
document.addEventListener("DOMContentLoaded", function(event) {
console.log(document.getElementById('loginPanel'));
proxy.initiate({
loginPanel: document.getElementById('loginPanel'),
msgPanel: document.getElementById('msgPanel'),
txtMsg: document.getElementById('txtMsg'),
txtLogin: document.getElementById('txtLogin'),
msgContainer: document.getElementById('msgContainer')
});
});
</script>
</head>
<body>
<div id="container">
<div id="loginPanel">
<div id="infoLabel">Type a name to join the room</div>
<div style="padding: 10px;">
<input id="txtLogin" type="text" class="loginInput"
onkeyup="proxy.login_keyup(event)" />
<button type="button" class="loginInput" onclick="proxy.login()">Login</button>
</div>
</div>
<div id="msgPanel" style="display: none">
<div id="msgContainer" style="overflow: auto;"></div>
<div id="msgController">
<textarea id="txtMsg"
title="Enter to send message"
onkeyup="proxy.sendMessage_keyup(event)"
style="height: 20px; width: 100%"></textarea>
<button style="height: 30px; width: 100px" type="button"
onclick="proxy.logout()">Logout</button>
</div>
</div>
</div>
</body>
</html>
chatroom.js
var CreateProxy = function(wsUri) {
var websocket = null;
var audio = null;
var elements = null;
var playSound = function() {
if (audio == null) {
audio = new Audio('content/sounds/beep.wav');
}
audio.play();
};
var showMsgPanel = function() {
elements.loginPanel.style.display = "none";
elements.msgPanel.style.display = "block";
elements.txtMsg.focus();
};
var hideMsgPanel = function() {
elements.loginPanel.style.display = "block";
elements.msgPanel.style.display = "none";
elements.txtLogin.focus();
};
var displayMessage = function(msg) {
if (elements.msgContainer.childNodes.length == 100) {
elements.msgContainer.removeChild(elements.msgContainer.childNodes[0]);
}
var div = document.createElement('div');
div.className = 'msgrow';
var textnode = document.createTextNode(msg);
div.appendChild(textnode);
elements.msgContainer.appendChild(div);
elements.msgContainer.scrollTop = elements.msgContainer.scrollHeight;
};
var clearMessage = function() {
elements.msgContainer.innerHTML = '';
};
return {
login: function() {
elements.txtLogin.focus();
var name = elements.txtLogin.value.trim();
if (name == '') { return; }
elements.txtLogin.value = '';
// Initiate the socket and set up the events
if (websocket == null) {
websocket = new WebSocket(wsUri);
websocket.onopen = function() {
var message = { messageType: 'LOGIN', message: name };
websocket.send(JSON.stringify(message));
};
websocket.onmessage = function(e) {
displayMessage(e.data);
showMsgPanel();
playSound();
};
websocket.onerror = function(e) {};
websocket.onclose = function(e) {
websocket = null;
clearMessage();
hideMsgPanel();
};
}
},
sendMessage: function() {
elements.txtMsg.focus();
if (websocket != null && websocket.readyState == 1) {
var input = elements.txtMsg.value.trim();
if (input == '') { return; }
elements.txtMsg.value = '';
var message = { messageType: 'MESSAGE', message: input };
// Send a message through the web-socket
websocket.send(JSON.stringify(message));
}
},
login_keyup: function(e) { if (e.keyCode == 13) { this.login(); } },
sendMessage_keyup: function(e) { if (e.keyCode == 13) { this.sendMessage(); } },
logout: function() {
if (websocket != null && websocket.readyState == 1) { websocket.close();}
},
initiate: function(e) {
elements = e;
elements.txtLogin.focus();
}
}
};

Java websocket creates new Instance with each client connection with server

I am using Java to create WebSocket Server And Javascript and HTML for the Client. The server starts successfully and can accept connection from WebSocket clients, But it is creating a new instance of the server every time a client connects.
Code of Server:-
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/websocketendpoint")
public class WsServer {
Set<Session> sessions = new HashSet<Session>();
int count = 0;
#OnOpen
public void onOpen(Session session){
System.out.println("Open Connection ...");
count+=1;
System.out.println(count); //On the logcat it shows only 1
sessions.add(session);
for(Session s: sessions)
{
System.out.println(s); //On the logcat it shows only session
}
}
#OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
#OnMessage
public String onMessage(String message){
System.out.println("Message from the client: " + message);
String echoMsg = "Echo from the server : " + message;
return echoMsg;
}
#OnError
public void onError(Throwable e){
e.printStackTrace();
}
}
Code Of Client:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
<form>
<input id="message" type="text">
<input onclick="wsSendMessage();" value="Echo" type="button">
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
</form>
<br>
<textarea id="echoText" rows="5" cols="30"></textarea>
<script type="text/javascript">
var webSocket = new WebSocket("ws://192.168.225.26:8080/WebSocketServerExample/websocketendpoint");
var echoText = document.getElementById("echoText");
echoText.value = "";
var message = document.getElementById("message");
webSocket.onopen = function(message){ wsOpen(message);};
webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wserror(message){
echoText.value += "Error ... \n";
}
</script>
</body>
</html>
And after the 2nd client connects it only shows 1 as a count and there is only one session is stored on the Set.
Technologies I am using:-
Tomcat v9.0
Eclipse Java EE IDE
Java For Server And JavaScript For Client
javax.websocket for WebSocket.
My question is how can we stop this and make clients connect to only one instance?
Look at the method names of WsServer. It is only intended for one client because the functions don't send a connection id with them. So make your counter static or move it to an other class.
that is the default behaviour.
Try adding #Singleton annotation before #ServerEndpoint.

How can I Download zip file using form submit, and get callback?

// Step 1
function doSubmit(data1, data2){
$("#dataForm").remove();
var form = '';
form += '<form name="dataForm" id="dataForm" action="" target="hiddenIframe" method="post" enctype="multipart/form-data" accept-charset="UTF-8">';
form += '<input type="text" name="data1" id="data1"/>';
form += '<input type="text" name="data2" id="data2"/>';
form += '<div name="dataFormTarget" id="dataFormTarget" style="display:none">';
form += '</div>';
form += '</form>';
$('body').append(form);
$("#dataForm data1").val(data1);
$("#dataForm data2").val(data2);
$("#dataForm").attr("action", "/download/fileDownload.do");
$("#dataForm").submit(function(event){
event.preventDefault();
$.ajax({
url : "/download/fileDownload.do",
async : true,
type : "POST",
data : {
"data1" : data1,
"data2" : data2
},
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
processData : true,
success : function(data){
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="testFile.zip";
link.click();
}
});
});
$("#dataForm").submit();
}
// Step 2
#RequestMapping(value = "/download/fileDownload.do")
public ModelAndView fileDownload(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws Exception {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Parameter inMap = rDictionary(request, response);
Parameter outMap = new Parameter();
Parameter errorMap = new Parameter();
File file = null;
try {
file = new File(inMap.get("data1"));
errorMap = Util.putErrorMap(ErrConst.ERROR_SUCCESS_CODE, null, inMap);
} catch (Exception e) {
e.printStackTrace();
}
mav.addObject("outMap", outMap);
mav = new ModelAndView("downloadView", "downloadFile", file);
return mav;
}
// Step 3
public class DownloadView extends AbstractView {
private static final Logger logger = LogManager.getLogger(DownloadView.class);
public DownloadView() {
setContentType("application/download; charset=utf-8");
}
#Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
File file = null;
try{
file = (File) model.get("downloadFile");
response.setContentType(getContentType());
response.setContentLength((int) file.length());
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out = response.getOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
FileCopyUtils.copy(fis, out);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ioe) {
}
}
}
out.flush();
}catch(Exception e){
logger.error("file not found Excpetion !!!["+ file.getPath() +"]");
}
}
}
Hi.
I'm trying to zip file download, using above code.
after download complete, I must need callback function for next download.
When run this code, download is occured.
but downloaded zip file was crashed..
I don't know what is wrong.
Please give me solution.
Thanks.
(Sorry for short english.)

Understand 304 response - not modified?

I am running the following script on the client-side and the script is failing to update, when there is change in the database. I debugged the script using DevTools and discovered my Jquery scripts are responding back as "304 not modified". Does this issue, indicate why the client-side content is failing to update.
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery-1.6.4.min.js"></script>
<script src="../Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.NotificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (role, descrip) {
// Add the message to the page.
$('#spanNewMessages').text(role);
$('#spanNewCircles').text(descrip);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications();
alert("Notifications have been sent.");
}).fail(function (e) {
alert(e);
});
//$.connection.hub.start();
});
</script>
<h1>New Notifications</h1>
<div>
<br />
<b>New <span id="spanNewMessages"></span> = role.</b><br />
<b>New <span id="spanNewCircles"></span> = descrip.</b><br />
</div>
Hub Class:
[HubName("NotificationHub")]
public class notificationHub : Hub
{
string role = "";
string descrip = "";
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
{
string query = "SELECT top 1 [role],[description] FROM [dbo].[User] order by uploadDate desc";
connection.Open();
SqlDependency.Start(GetConnectionString());
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
role = dt.Rows[0]["role"].ToString();
descrip = dt.Rows[0]["description"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
Clients.All.RecieveNotification(role, descrip);
}
[HubMethodName("onStatusChanged")]
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
{
notificationHub nHub = new notificationHub();
nHub.SendNotifications();
}
}
Please advice. Thank you.

Categories