Send image socket io and android - javascript

I am a beginner in socket.io. I have been used a library
https://www.npmjs.com/package/socket.io-stream
We were successfully uploaded images using the browser. But now, I want to upload images from android application. If anyone have android code please give me ..
https://github.com/socketio/socket.io-client-java/issues/29
I have been searching on google, but not found any proper solution.

var imageBuffer = customJs.decodeBase64Image(base64Data);
var imageTypeDetected = imageBuffer.type.match(/\/(.*?)$/);
var filename = 'profile-' + Date.now() + '.' + imageTypeDetected[1];
// config.uploadImage --- Folder path where you want to save.
var uploadedImagePath = config.uploadImage + filename;
try {
fs.writeFile(uploadedImagePath, imageBuffer.data, function () {
dbMongo.updateImage({email: decoded.email, user_id: decoded.userId, 'profile_picture': config.showImagePath + filename}, function (res) {
if (res.error) {
socket.emit('set_update_image', {'error': 1, 'message': 'Error!' + res.message, 'data': null, 'status': 400});
} else {
console.log(res);
socket.emit('set_update_image', res);
}
});
});
} catch (e) {
socket.emit('set_update_image', {'error': 1, 'message': 'Internal server error ' + e, 'data': null, 'status': 400});
}
From other file call a function
exports.decodeBase64Image = function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};
if (matches.length !== 3)
{
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}

For the upload image from android using socket you need to send image as base64 string,
Following is the example for convert Image into base64 then you send data same as another paramaters.
String base64Image = getBase64Data(dirPath + "/" + fileName);
public String getBase64Data(String filePath) {
try {
InputStream inputStream = new FileInputStream(filePath);//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
}
bytes = output.toByteArray();
return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

In android, you need to encode the image by using Base64
public void sendImage(String path)
{
JSONObject sendData = new JSONObject();
try{
sendData.put("imageData", encodeImage(path));
socket.emit("image",sendData);
}catch(JSONException e){
}
}
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
In server side, receive image and decode it
socket.on("image", function(info) {
var img = new Image();
img.src = 'data:image/jpeg;base64,' + info.imageData;
});

Related

.NET Framework MVC Large file upload

I am trying to upload large binary files from a web client to a .NET 4.6.1 Framework MVC API. These files could range anywhere from 5GB to 20GB.
I have tried splitting the file into chunks to upload each chunk and merge the results at the end, but the merged file is always corrupted. If I work with small files and don't split, the binary will work correctly. However, when I split and merge the file is "corrupted". It won't load or behave as expected.
I have looked all over and haven't seen a proper solution to this so i'm hoping someone can help me here.
I followed this https://forums.asp.net/t/1742612.aspx?How+to+upload+a+big+file+in+Mvc, but I can't get it to work and the corrected solution was never posted. I am keeping track of the order of files before merging on the server.
Javascript (Call to uploadData is made to initiate)
function uploadComplete(file) {
var formData = new FormData();
formData.append('fileName', file.name);
formData.append('completed', true);
var xhr3 = new XMLHttpRequest();
xhr3.open("POST", "api/CompleteUpload", true); //combine the chunks together
xhr3.send(formData);
return;
}
function uploadData(item) {
var blob = item.zipFile;
var BYTES_PER_CHUNK = 750000000; // sample chunk sizes.
var SIZE = blob.size;
//upload content
var start = 0;
var end = BYTES_PER_CHUNK;
var completed = 0;
var count = SIZE % BYTES_PER_CHUNK == 0 ? SIZE / BYTES_PER_CHUNK : Math.floor(SIZE / BYTES_PER_CHUNK) + 1;
while (start < SIZE) {
var chunk = blob.slice(start, end);
var xhr = new XMLHttpRequest();
xhr.onload = function () {
completed = completed + 1;
if (completed === count) {
uploadComplete(item.zipFile);
}
};
xhr.open("POST", "/api/MultiUpload", true);
xhr.setRequestHeader("contentType", false);
xhr.setRequestHeader("processData", false);
xhr.send(chunk);
start = end;
end = start + BYTES_PER_CHUNK;
}
}
Server Controller
//global vars
public static List<string> myList = new List<string>();
[HttpPost]
[Route("CompleteUpload")]
public string CompleteUpload()
{
var request = HttpContext.Current.Request;
//verify all parameters were defined
var form = request.Form;
string fileName;
bool completed;
if (!string.IsNullOrEmpty(request.Form["fileName"]) &&
!string.IsNullOrEmpty(request.Form["completed"]))
{
fileName = request.Form["fileName"];
completed = bool.Parse(request.Form["completed"]);
}
else
{
return "Invalid upload request";
}
if (completed)
{
string path = HttpContext.Current.Server.MapPath("~/Data/uploads/Tamp");
string newpath = Path.Combine(path, fileName);
string[] filePaths = Directory.GetFiles(path);
foreach (string item in myList)
{
MergeFiles(newpath, item);
}
}
//Remove all items from list after request is done
myList.Clear();
return "success";
}
private static void MergeFiles(string file1, string file2)
{
FileStream fs1 = null;
FileStream fs2 = null;
try
{
fs1 = System.IO.File.Open(file1, FileMode.Append);
fs2 = System.IO.File.Open(file2, FileMode.Open);
byte[] fs2Content = new byte[fs2.Length];
fs2.Read(fs2Content, 0, (int)fs2.Length);
fs1.Write(fs2Content, 0, (int)fs2.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + " : " + ex.StackTrace + " " + file2);
}
finally
{
if(fs1 != null) fs1.Close();
if (fs2 != null)
{
fs2.Close();
System.IO.File.Delete(file2);
}
}
}
[HttpPost]
[Route("MultiUpload")]
public string MultiUpload()
{
try
{
var request = HttpContext.Current.Request;
var chunks = request.InputStream;
string path = HttpContext.Current.Server.MapPath("~/Data/uploads/Tamp");
string fileName = Path.GetTempFileName();
string newpath = Path.Combine(path, fileName);
myList.Add(newpath);
using (System.IO.FileStream fs = System.IO.File.Create(newpath))
{
byte[] bytes = new byte[77570];
int bytesRead;
while ((bytesRead = request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
{
fs.Write(bytes, 0, bytesRead);
}
}
return "test";
}
catch (Exception exception)
{
return exception.Message;
}
}

How to serve an audio file from java API to the front end?

I'm trying to send a request to an API through (t = textToSpeechService.callAPI(tmp);) and it returns an audio file. I tried serving it to the front end through the OutputStream but how do I actually serve the actual file i.e. wav file, since I need it afterwards to play and pause in the front end?
public Clip callAPI(Source src){
URL url;
Clip result = null;
AudioInputStream sound = null;
{
try {
url = new URL(" http://api.voicerss.org/?key=" + keyAPI + "&hl=" + src.getLang() + "&src=" + src.getSrc());
sound = AudioSystem .getAudioInputStream(url); //here i have the audio
Object sound2 = AudioSystem.getAudioInputStream(url);
AudioFormat at = sound.getFormat();
result = AudioSystem.getClip();
result.open(sound);
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (LineUnavailableException e) {
e.printStackTrace();
}
}
return result;
}
Clip t = null;
AudioInputStream ais = null;
private TextToSpeechService textToSpeechService;
public Clip theFunction(#RequestParam String src, HttpServletRequest request){
//if(src == request.getSession().getAttribute("input")){
Source tmp = new Source();
tmp.setSrc(src);
t = textToSpeechService.callAPI(tmp);
t.start();
return t;
}
public void getHere(#RequestParam String src, HttpServletRequest request, HttpServletResponse response) throws IOException {
Source tmp = new Source();
tmp.setSrc(src);
ais = textToSpeechService.callAPI2(tmp);
OutputStream os = response.getOutputStream();
BufferedInputStream bf = new BufferedInputStream(ais);
response.setContentType("audio/wav");
int readBytes = 0;
while((readBytes= bf.read())!= -1){
os.write(readBytes);
}
}

how to show image from server in javascript?

I am making Thumbnail View pages.
I stored thumbnail images external folder(C:/temp/image) and I get them from server as byte data.
now I want to convert this data into image in javascript and show in HTML.
so I tried to make blob URL using these byte data. But I got error "FILE NOT FOUND"
Here is my code. Please let me know what i'm missing
(It is Spring boot and angular.js )
Service
public List<Map<String, Object>> listRecentWithInfo( int userid) throws IOException, SerialException, SQLException {
List<Map<String, Object>> recentList = dashboardDao.listRecentWithInfo( userid);
for (Map<String, Object> map : recentList) {
int dashboardid = (int) map.get( "DASHBOARDID");
FileInputStream is = null;
BufferedImage bi = null;
ByteArrayOutputStream bao= null;
byte[] imageByte = null;
ResponseEntity<byte[]> res = null;
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
if (thumbnailDao.findOne( dashboardid) != null) {
String path = thumbnailPath + thumbnailDao.getOne( dashboardid).getFileName();
is = new FileInputStream(path);
bi = ImageIO.read(is);
System.out.println(bi.getType());
bao = new ByteArrayOutputStream();
ImageIO.write(bi, "png", bao);
imageByte = bao.toByteArray();
res = new ResponseEntity<>(imageByte, headers, HttpStatus.OK);
}
map.put("THUMBNAIL", res);
}
return recentList;
}
js
$http.get("app/dashboard/recentWithInfo").then( function( rtn) {
rtn.data.map(item=> {
if (item.THUMBNAIL) {
var bytes = new Uint8Array(item.THUMBNAIL.body / 2);
for (var i = 0; i < item.THUMBNAIL.body; i += 2) {
bytes[i / 2] = parseInt(item.THUMBNAIL.body.substring(i, i + 2), /* base = */ 16);
}
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/png'});
var imageUrl = URL.createObjectURL(blob);
URL.revokeObjectURL(imageUrl);
item.THUMBNAIL = imageUrl;
}
});
$scope.items = rtn.data;
console.log(rtn.data);
});
});
Thanks in advance!
I Got a solution By myself
I realized that I can convert Byte Data into Base64 just like that
"data:image/png;base64," + item.THUMBNAIL.body;
and this BASE64 encoded data can be used as Image source in HTML!

Download and save file in browser's local storage

I have a Java web app that serves a file:
#RequestMapping(value = "/pdf/download", method = RequestMethod.GET)
public void download(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam(value = "id", required = true) Long id) throws IOException {
File pdfFile = pdfFileManager.getFromId(id);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=download");
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = null;
OutputStream responseOutputStream = null;
try {
fileInputStream = new FileInputStream(pdfFile);
responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
responseOutputStream.flush();
} finally {
fileInputStream.close();
responseOutputStream.close();
}
}
I retrieve the file in the client and base64 encode it using FileReader:
$.ajax({
url: "/pdf/download?id=" + id,
dataType: "application/pdf",
processData: false
}).always(function(response) {
if(response.status && response.status === 200) {
savePdf(response.responseText, "download_" + id);
}
});
function savePdf(pdf, key) {
var blob = new Blob([pdf], {type: "application/pdf"});
var fileReader = new FileReader();
fileReader.onload = function (evt) {
var result = evt.target.result;
try {
localStorage.setItem(key, result);
} catch (e) {
console.log("Storage failed: " + e);
}
};
fileReader.readAsDataURL(blob);
}
The problem is that the value saved in the local storage is not correct. The encoded data differs from the one i get when i upload the PDF using this snip. I don't know if the problem is how i serve the file or the encoding process in the client.
The value stored is something like this
data:application/pdf;base64,JVBERi0xLjQKJe+/ve+/ve+/ve+/vQoxIDAgb...
instead of
data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Ue...
Solved the problem setting the request's response type to blob:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/pdf/download?id=" + id);
xhr.responseType = "blob";
xhr.onload = function() {
if(xhr.status && xhr.status === 200) {
savePdf(xhr.response, "download_" + id);
}
}
xhr.send();
function savePdf(pdf, key) {
var fileReader = new FileReader();
fileReader.onload = function (evt) {
var result = evt.target.result;
try {
localStorage.setItem(key, result);
} catch (e) {
console.log("Storage failed: " + e);
}
};
fileReader.readAsDataURL(pdf);
}

Encoding a image to base64 and upload to web service in Phonegap

In my PhoneGap project, I use navigator.device.capture.captureImage(captureSuccess, captureError, {limit : 1}); to take a picture. In captureSucces function, I get de MediaFile, and I encode it to base64 with this:
var file="";
var datafile=mediaFiles[0];
var reader = new FileReader();
reader.onload = function(evt){
file=evt.target.result;
};
reader.readAsDataURL(datafile);
I send this file to a REST Web Service, where I decode the file and save in a folder:
if (files != null) {
FileOutputStream fileOutputStream = null;
try {
byte[] byteFichero = Base64.decodeBase64(files);
System.out.println("ARCHIVO " + byteFichero);
File fich = new File(pathFichero.toString());
fich.createNewFile();
fileOutputStream = new FileOutputStream(fich);
fileOutputStream.write(byteFichero);
System.out.println("Fichero almacenado ok");
} catch (Exception e) {
System.out.println("Excepcion alamacenando fichero "
+ e.getMessage() + " " + pathFichero);
return respuesta;
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException ex) {
Logger.getLogger(
GestionFicheroObjetoService.class.getName())
.log(Level.SEVERE, null, ex);
}
pathFichero.delete(0, pathFichero.length());
}
}
Unfortunately, I get an empty image(1 KB). This is because the file value is not correct, it contains:
{"name":"1385711756945.jpg",
"fullPath":"file:///storage/sdcard0/DCIM/Camera/1385711756945.jpg",
"type":"image/jpeg",
"lastModifiedDate":1385711757000,
"size":2785413,
"start":0,
"end":0}
and when I encode this, I get a little base64 code:
[B#877d81
In other examples, they always use input type file to get the file (http://thiscouldbebetter.wordpress.com/2013/07/03/converting-a-file-to-a-base64-dataurl-in-javascript/) but I have to get the file from Camera.
What is the problem? Some other solution?
Thank you very much.
i am also facing this issue. i got solution after long time search
camera success function:
function capturesuceess(mediafiles){
var uploadimageurl= mediafile
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, rfail);
window.resolveLocalFileSystemURI(uploadimageurl, onResolveSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
console.log(fileSystem.name);
}
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
function onResolveSuccess(fileEntry) {
filenameofajax=fileEntry.name;
var efail = function(evt) {
console.log("File entry error "+error.code);
};
var win=function(file) {
console.log(file);
alert(bytesToSize(file.size));
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("read success");
console.log(evt.target.result);
var basestr=evt.target.result;
basestr= basestr.substr(basestr.indexOf("base64,")+7,basestr.length);
console.log(basestr);// this is a base64 string
};
reader.readAsDataURL(file);
};
fileEntry.file(win, efail);
}
try this working fine. and also u write efail and fail function with empty enjoy with phonegap
The best way to do this is using navigation.camera:
https://gist.github.com/pamelafox/2173589

Categories