writing pdf from javascript/cordova - javascript

In our mobile application (cordova+html4) we have a requirement to display the PDF from a stream. We have a service which returns pdf stream. We would like to store that stream to a temp folder location of the mobile and display the PDF.
The below sample java sample java code does the exact thing what I need. But how can I achive this functionality on java script? I mean reading a binary stream in java script.
String fileURL = "https://1/////4/xyz";
String saveDir = "D:/Works";
try {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("TOKEN",
"ghZtxnPfpJ63FgdT/59V+5zFTKHRdwm6rIfGJC+0B5W5CJ9pG33od7l+/L6S8R56");
int responseCode = httpConn.getResponseCode();
System.out.println("Reseponse Code = " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn
.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(
saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
httpConn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Thre's two libraries that you may want to have a look at :
jsPDF if you're trying to generate pdf from javascript and
pdf.js if you're trying to implement a pdf viewer in your interface.
One of those two should do the trick for you.

Related

How to upload multiple images from front-end using JavaScript, jQuery, Ajax in JSP file and send it into Spring Boot Controller?

I am working on a spring boot web application, where I want to upload multiple images of a product at a time along with other fields (for example product name, SKU code, category, tags, subcategory, etc). I have written code for RESTful API to upload multiple images and it is working perfectly for me. I tested API using postman and it is working fine. But, I don't know how to do it from the front end. I am showing you my front-end code below, where I am sending a single image to my controller using Ajax.
$("#file").change(function(){
var formData = new FormData();
var fileSelect = document.getElementById("file");
if(fileSelect.files && fileSelect.files.length == 1) {
var file = fileSelect.files[0];
formData.set("file",file,file.name);
}else{
$("#file").focus();
return false;
}
var request = new XMLHttpRequest();
try {
request.onreadystatechange=function() {
if(request.readyState==4) {
var v = JSON.parse(request.responseText);
if(v.status==="OK") {
alert("Product Image Uploaded Successfully")
document.getElementById('imagepath').value = v.response;
}
}
}
request.open('POST',"<%=AkApiUrl.testuploadfile%>");
request.send(formData);
} catch(e) {
swal("Unable to connect to server","","error");
}
});
As I told you, the above code is to send a single file at a time. I am showing you my API controller code also:
#RequestMapping(value = AkApiUrl.testuploadfile, method = { RequestMethod.POST, RequestMethod.GET }, produces = {MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> testuploadfile(HttpServletRequest request, #RequestParam("files") MultipartFile[] files) {
CustomResponse = ResponseFactory.getResponse(request);
String imgurl = "NA";
try {
String path = Constants.webmedia;
String relativepath = "public/media/";
System.out.println("Here is the image: ");
List<MultipartFile> multifile = Arrays.asList(files);
if( null != multifile && multifile.size()>0) {
for (int i=0; i < multifile.size(); i++) {
String filename = files[i].getOriginalFilename();
String extension = filename.substring(filename.lastIndexOf("."), filename.length());
int r = (int )(Math.random() * 500 + 1);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = new Date();
String formatdate = format.format(date);
formatdate = "ECOM" + formatdate + r;
byte[] bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(path + File.separator + formatdate + extension)));
stream.write(bytes);
stream.flush();
stream.close();
String newimgurl = relativepath + formatdate + extension;
imgurl = imgurl+"##"+newimgurl;
if(imgurl != null) {
CustomResponse.setResponse(imgurl);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
This API is working fine, I am getting desired response. But I do not know how should I implement this thing on the JSP page. Please, any suggestions would be appreciated.

Get filename and length from blob stream

I am using websockets to send a file from my c# server to my browser. I added the file name and filebytelength along with the file in the bytestream.
My c# code to include file name in the byte stream
string filename = "#\C:\Users\Username\Downloads\RAW1MB data.txt";
string shortName = System.IO.Path.GetFileName(FileName);
byte[] fileNameByte = Encoding.UTF8.GetBytes(shortName);
byte[] fileNamelen = BitConverter.GetBytes(shortName.Length);
byte[] filedata = File.ReadAllBytes(FileName);
byte[] senddata = new byte[4 + fileNameByte.Length + filedata.Length];
fileNamelen.CopyTo(senddata, 0);
fileNameByte.CopyTo(senddata, 4);
filedata.CopyTo(senddata, 4 + fileNameByte.Length);
await webSocket.SendAsync(new ArraySegment<byte>(senddata,0,senddata.Length),WebSocketMessageType.Binary,true,CancellationToken.None );
This is my Javascript included in my HTML
websocket.onmessage = function (e) {
if(e.data instanceof Blob){
window.alert("Getting file");
var filedata = e.data;
var filenameLen = filedata.slice(0,4);
Console.log(filenamelen);// I am getting Blob{ size: 4 ,type: ""}
}
else{
writeToScreen("<span>RESPONSE: " + e.data + "</span>");
}
};
From the console.log I am getting Blob{ size:4,type :""}.
How do I get the integer and string from first 4 bytes and the following respectively?
So without getting the filenamelen I am unable to get the filename as well.

Write data into JS file and download it in ZIP file format

In my JSP, I have a button named "Download Zip file". When I click the button, I want to fetch data from the database and write it into a JS file and keep it inside a folder and download folder in ZIP format. I am using struts2.
How can I do this?
One way is to serve binary data from a servlet. Something like this:
byte[] zipFileBytes = ...;// generate the zip file and get the bytes
response.setContentType("application/octet-stream");
response.getOutputStream().write(zipFileBytes );
Then use a standard anchor element to download the file:
<a src="url to your servlet">download the file</a>
You might need to play with this a little bit to match your exact use case.
Try this : code to download file as a Zip
ServletOutputStream servletOS = null;
String zipFileName = null;
try {
servletOS = response.getOutputStream();
final ResourceResolver resolver = request.getResourceResolver();
zipFileName = FileDownloadHelper.getDownloadZipFileName();
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=" + zipFileName);
servletOS.write(FileDownloadHelper.prepareZipDownloadOutputStream(servletOS, documentUrls));
} finally {
if (servletOS != null) {
servletOS.flush();
servletOS.close();
}
}
public static byte[] prepareZipDownloadOutputStream(final ServletOutputStream outputStream,
final List<String> docUrls) throws IOException {
final byte[] buf = new byte[2048];
String fileName;
ZipOutputStream zipOutputStream = null;
InputStream isInputStream = null;
try {
zipOutputStream = new ZipOutputStream(outputStream);
for (final String docUrl : docUrls) {
LOGGER.info("Reading file from DAM : " + docUrl);
// read this file as input stream
isInputStream = new FileInputStream(docUrl);
if (isInputStream != null) {
fileName = getFileNameFromDocumentUrl(docUrl);
// Add ZIP entry to output stream.
zipOutputStream.putNextEntry(new ZipEntry(fileName));
int bytesRead;
while ((bytesRead = isInputStream.read(buf)) != -1) {
zipOutputStream.write(buf, 0, bytesRead);
}
zipOutputStream.closeEntry();
} e
}
} finally {
if (zipOutputStream != null) {
zipOutputStream.flush();
zipOutputStream.close();
}
if (isInputStream != null) {
isInputStream.close();
}
}
LOGGER.info("Returning buffer to be written to response output stream");
return buf;
}
public static String getFileNameFromDocumentUrl(final String docUrl) {
return docUrl
.substring(docUrl.lastIndexOf("/") + 1, docUrl.length());
}

Upload a file on Button click in asp

I am working on classic ASP with WinCE OS. I want to upload a file from WinCE and Save in the local machine. Please share the necessary JScript function for file upload which i can put it in a include file. Thank you.
Better way is to use any JavaScript library.. like jQuery..
Here are the file upload examples..
http://pixelcone.com/jquery/ajax-file-upload-script/
How can I upload files asynchronously?
Cheers :)
I have no information about asp classic but I have used Asp.net and you can use asp to receive file in order to upload file from wince use can develop app using c# here is an example.
Its client WinCE Application Code Function Upload(string Path, String FileName) takes File Path and File Name as Input and Post it to web page
#region Upload
public bool Upload(string FilePath, string FileName)
{
string Url = "HTTP://test.mtsonweb.com/fileupload.ashx"; // Change it to your page name
string BytesConfirmedReceived = "";
int BytesSent = 0;
bool Ret = false;
ASCIIEncoding encoding = new ASCIIEncoding();
try
{
if (File.Exists(FilePath +"\\"+ FileName) == false) { return true; }
//FileInfo oInfo = new FileInfo(FilePath + "\\" + FileName);
//BytesSent = Convert.ToInt32(oInfo.Length.ToString());
Url += "?myfile=" + FileName.Trim();
FileStream fr = new FileStream(FilePath + "\\" + FileName, FileMode.Open);
BinaryReader r = new BinaryReader(fr);
byte[] FileContents = r.ReadBytes((int)fr.Length);
BytesSent = FileContents.Length;
r.Close();
fr.Close();
WebRequest oRequest = WebRequest.Create(Url);
oRequest.Method = "POST";
oRequest.Timeout = 15000;
oRequest.ContentLength = FileContents.Length;
Stream oStream = oRequest.GetRequestStream();
BinaryWriter oWriter = new BinaryWriter(oStream);
oWriter.Write(FileContents);
oWriter.Close();
oStream.Close();
WebResponse oResponse = oRequest.GetResponse();
BytesConfirmedReceived = new StreamReader(oResponse.GetResponseStream(),
Encoding.Default).ReadToEnd();
oResponse.Close();
if (BytesSent.ToString() == BytesConfirmedReceived.Trim())
{
Ret = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Ret;
}
#endregion
Now of you page you can handle file uploaded using script whatever you want, I have used asp.net with c# as back-end and below is the source of page:
<%# WebHandler Language="C#" Class="FileUpload" %>
using System;
using System.Xml;
using System.Data;
using System.Web;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
public class FileUpload : IHttpHandler
{
public void ProcessRequest(HttpContext oContext)
{
int BytesSent = 0;
//string LocalPath = #"C:\Inetpub\wwwroot\";
string MyFile = "";
try
{
MyFile = oContext.Request["myfile"].ToString().Trim();
MyFile = HttpContext.Current.Server.MapPath("~/Demo/Files/" +
ASCIIEncoding encoding = new ASCIIEncoding();
BytesSent = oContext.Request.TotalBytes;
Class1 obj = Class1.GetInstance();
obj.FileName = MyFile;
obj.FileLength = BytesSent;
byte[] InComingBinaryArray =
oContext.Request.BinaryRead(oContext.Request.TotalBytes);
obj.Data = InComingBinaryArray;
if (File.Exists(MyFile) == true)
{
File.Delete(MyFile);
}
FileStream fs = new FileStream(MyFile, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(InComingBinaryArray);
w.Close();
fs.Close();
FileInfo oInfo = new FileInfo(MyFile);
long a = (long)BytesSent;
oContext.Response.Write(oInfo.Length.ToString());
}
catch (Exception err) { oContext.Response.Write(err.Message); }
}
public bool IsReusable { get { return true; } }
}

Images not reflected in the gallery after saved

if (action.equals("saveToGallery")) {
JSONObject obj = args.getJSONObject(0);
String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null;
String imageName = obj.has("imageName") ? obj.getString("imageName") : null;
String savedImgSrc = saveImageToGallery(imageSource, imageName);
Log.v("SAve To Gallery ", "saved file url: " + savedImgSrc);
return new PluginResult(PluginResult.Status.OK);
}
return new PluginResult(PluginResult.Status.INVALID_ACTION);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
public String saveImageToGallery(String imgSrc, String imgName) {
Log.v("Save To Gallery ", "image SRc: " + imgSrc + " , image Name:"
+ imgName);
Context ctx = this.ctx;
AssetManager assmgr = ctx.getAssets();
File tempDir = new File("/sdcard/HarmonyDayApp/wallpapers/");
tempDir.mkdirs();
File file = new File(tempDir, imgName);
try {
InputStream is = null;
is = assmgr.open("www/" + imgSrc);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
is.close();
os.close();
} catch (IOException ex) {
Log.w("ExternalStorage", "Error writing " + file, ex);
}
return file.getAbsolutePath();
}
This is the code I am using to save the image to the device gallery. However, after the image is saved, if i check the gallery imeediately, the image is not there. It comes when i reload the application, or the gallery after sometime. Any suggestion to this problem will be helpful.
Try this:
After adding your image in gallery you need to broadcast
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://”+
Environment.getExternalStorageDirectory())));
Hopefully it will work for you. :)
you need to scan media manually, after your image has been saved, by following code:
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});

Categories