Make Byte array To File for download Using ajax - javascript

Now i'm trying to make a file download with ajax but when i open downloaded file, picture viewer said this file format is not supported
how can i fix it?
it is javascript part
function downloadFile(file_no){
const xhr = new XMLHttpRequest();
xhr.open("POST","/timewizard/file/download/"+file_no);
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200){
if (xhr.responseText != null && xhr.responseText != "" && xhr.responseText != '[]'){
let item = JSON.parse(xhr.responseText);
console.log(item);
let bytes = new Uint8Array(item.bytes.length);
let length = bytes.length;
for (let i = 0; i < length; i++){
bytes[i] = item.bytes.charCodeAt(i);
}
// let blob = new Blob([item.bytes], {type: item.mime});
let blob = new Blob(bytes, {type: item.mime});
console.log(blob);
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
let fileName = "timewizard_" + new Date().getTime();
link.download = fileName + "." + item.extension;
link.click();
// return xhr.responseText;
}
}
}
}
and java class file part
#RequestMapping(value="/download/{file_no}")
// public byte[] fileDownload(HttpServletRequest request, HttpServletResponse response, #PathVariable int file_no) {
public Map<String, Object> fileDownload(HttpServletRequest request, HttpServletResponse response, #PathVariable int file_no) {
Map<String, Object> answer = new HashMap<String, Object>();
FileUploadDto dto = fileUploadBiz.selectOne(file_no);
String extension = FilenameUtils.getExtension(dto.getFile_name());
String mime_front = (dto.getFile_type().equals("P"))?"image":"video";
String mime_back = (extension.toLowerCase().equals("jpg"))?"jpeg":extension.toLowerCase();
answer.put("mime", mime_front + "/" + mime_back);
answer.put("extension", extension);
byte[] down = null;
try {
String uploadPath = WebUtils.getRealPath(request.getSession().getServletContext(), "/resources/image");
File file = new File(uploadPath + "/" + dto.getFile_name());
down = FileCopyUtils.copyToByteArray(file);
String filename = new String(file.getName().getBytes(), "8859_1");
// response.setHeader("Content-Disposition", "attachment; filename=\""+filename +"\"");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
answer.put("bytes", down);
// return down;
return answer;
}
The commented part was a method of creating a form and submit button in html and directly spread?returning a byte array, and it actually works nice.
but I want to use a blob.
is there any idea for using blob? or other nice one?
Thanks!

Related

Kleopatra: Decryption failed: invalid data

For encrypting files I use PKCS # 7 and the Javascript bundle forge.pki.
var forge = require('node-forge');
var contentBuffer = forge.util.createBuffer( forge.util.decode64( "fasdasd asdasdasda" ));
var cert = forge.pki.certificateFromPem(certPem);
var p7 = forge.pkcs7.createEnvelopedData();
p7.addRecipient(cert);
p7.content = contentBuffer;
console.log("Encrypt...");
p7.encrypt();
var asn1Cert = p7.toAsn1();
var derBuffer = forge.asn1.toDer(asn1Cert);
var p7mContent = derBuffer.toHex();
console.log(p7mContent);
I copy the hex value into my Java class as a string constant. Java saves then converts this into a .p7m file and stores it locally for me.
public void writeDocumentContent(String filename) throws Exception {
byte[] encryptedMessage = getP7MBytes(hex);
InputStream inputStream = new ByteArrayInputStream(encryptedMessage);
handleTransfer(inputStream, TransferKanal.HTML5);
}
private static byte[] getP7MBytes(String p7m) {
int len = p7m.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(p7m.charAt(i), 16) << 4) + Character.digit(p7m.charAt(i + 1), 16));
}
return data;
}
private void handleTransfer(InputStream inputStream, TransferKanal kanal) throws Exception {
String path = "C:TEMP/padline";
createDirectory(path);
String filename = "example." + kanal.getFileExtension();
File targetFile = new File(path, filename);
provideTransferData(inputStream, targetFile);
}
private void provideTransferData(InputStream inputStream, File targetFile) throws Exception {
try (InputStream bInputStream = new BufferedInputStream(inputStream, 20 * 8192)) {
provide(bInputStream, targetFile);
} catch (IOException e) {
throw new Exception("error while reading/writing transfer data", e);
}
}
private boolean createDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
file.mkdirs();
return true;
}
return false;
}
private void provide(InputStream is, File finalFile) throws Exception {
try {
File destFile = new File(finalFile.getAbsolutePath());
FileOutputStream buffer = null;
try {
buffer = new FileOutputStream(destFile);
int nRead;
byte[] buf = new byte[2 * 16384];
while ((nRead = is.read(buf, 0, buf.length)) != -1) {
buffer.write(buf, 0, nRead);
}
} catch (Exception e) {
throw new Exception("provision location corrupted", e);
} finally {
if (buffer != null) {
buffer.close();
}
}
} catch (IOException e) {
throw new Exception("error copying file", e);
}
}
Before, I create a bundle of the certificate and the private key via openSSL with following command:
openssl pkcs12 -export -inkey private.key -in public.cert -out certificate.pfx
and imported it into Kleopatra as a .pfx file. Then I have the generated (encrypted) p7m file to decrypt in Cleopatra and pushed the following error message:
Decryption failed: invalid data

I want to print to pdf file in javascript, where outputstream and pdfwriter

I am trying to create a PDF from a server-side controller (report) (ireport) with ajax (and so on), and try to return the data to pdfwriter, servletoutputstream, and httpservletresponse. (I do not know exactly what I'm doing, but I'm doing it this way).
The original purpose was to send a server-side pdf file to the client, find the printer and print without a preview window.
Among them, I wrote 'application / pdf' on the server side and 'datetype: text' on the client side ajax (there is an error if I do not use ajax datatype: text)
If you print the results to the console, they will only be listed as unknown code.
Currently I am trying to put it into an iframe frame.
Question!
1. What should I do to use the text string sent to server -> client as pdf or script code?
(I have already asked you two weeks ago)
2. How do I send a pdf to server -> client? I would like to apply it to the screen by expressing it directly in code instead of downloading it. To print out.
ENG)>
// I used ajax only, because I dont know any other way
$.ajax({
url : "url",
data : JSON.stringify(data),
dataType : "text",
type: "POST",
contentType: 'application/json; charset=utf-8',
async : false,
success: function(result){
// I want to view PDF contents and directly print to PDF.
}
})
public Params createIbExItemLabelReport(HttpServletRequest resq, HttpSession session, Params inParams, HttpServletResponse resp) throws Exception{
Params outParams = ParamsFactory.createParams(inParams);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "0");
List<DataRow> list = new ArrayList<DataRow>();
String reportCd = "15";
String fileName = "ibExItemLabel"+reportCd+"Report";
String nullJpgFile = "";
int flag = 0;
int nullCheck = 0;
for(DataRow dr : inParams.getDataTable("dt_data")){
String imgName = "c:\\WMS\\LABEL\\FIAC021_" +reportCd + ".jpg";
File f = new File(imgName);
if (!f.isFile()) {
flag = 1;
if(nullCheck != 0){
nullJpgFile += ", ";
}
nullJpgFile += "FIAC021";
nullCheck++;
continue;
}
String bacodeCd = "FIAC02120180416001";
dr.setParam("imgName", imgName);
dr.setParam("bacodeCd", bacodeCd);
list.add(dr);
}
if(flag == 1){
outParams.setParam("ERROR_FILE", "제품코드 ["+nullJpgFile+"]의 라벨 사이즈" + reportCd + "인 파일이 존재하지않습니다.");
return outParams;
}
String appPath = session.getServletContext().getRealPath("/");
String pdfPath = null;
List<DataRow> list2 = new ArrayList<DataRow>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).getInt("printQty"); j++){
list2.add(list.get(i));
}
}
Report report = new Report();
pdfPath = report.reportToPdf(session, list2, fileName);
outParams.setParam("fileName", pdfPath);
System.out.println("Found! FileName is ' : "+ pdfPath);
pdfPath = appPath + pdfPath;
pdfPath = pdfPath.replace("//", "/");
ServletOutputStream servletOutput = resp.getOutputStream();
PdfWriter pdfWriter = null;
StringBuffer pdfJs = null;
ByteArrayOutputStream pdfOutput = null;
InputStream pdfInput = null;
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfOutput = convertPDFToByteArrayOutputStream(pdfPath);
int printCopy = 1;
if (printCopy == 0) {
printCopy = 1;
}
if (printCopy > 1) {
PdfCopyFields pdfPrintCopy = new PdfCopyFields(pdfOutput);
for (int i = 0; i < printCopy; i++) {
pdfPrintCopy.addDocument(new PdfReader(outputToInputStream(pdfOutput)));
}
pdfPrintCopy.close();
}
pdfInput = outputToInputStream(pdfOutput);
pdfReader = new PdfReader(pdfInput);
pdfStamper = new PdfStamper(pdfReader, servletOutput);
pdfWriter = pdfStamper.getWriter();
String printerNm = "SINDOH D410 Series PCL";
pdfWriter.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
pdfJs = new StringBuffer();
pdfJs.append("var param=this.getPrintParams();\r");
pdfJs.append("param.printerName=\"").append(printerNm).append("\";\r");
pdfJs.append("param.interactive=param.constants.interactionLevel.silent;\r");
pdfJs.append("param.pageHandling=param.constants.handling.shrink;\r");
pdfJs.append("this.print(param);\r");
pdfJs.append("this.closeDoc();");
pdfWriter.addJavaScript(pdfJs.toString(), false);
servletOutput.flush();
Log.debug("servletOutput " );
if (pdfInput != null) {
try {
pdfInput.close();
} catch (Exception e) {
}
pdfInput = null;
}
if (pdfOutput != null) {
try {
pdfOutput.close();
} catch (Exception e) {
}
pdfOutput = null;
}
if (pdfReader != null) {
pdfReader.close();
pdfReader = null;
}
pdfWriter = null;
try {
if (pdfStamper != null) {
pdfStamper.close();
pdfStamper = null;
}
} catch (Exception e) {
}
resp.setHeader("Content-Disposition", "inline; filename="+pdfPath);
resp.setHeader("Content-Type", "application/pdf; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
Log.debug("before outParams " );
return outParams;
}
private InputStream outputToInputStream(ByteArrayOutputStream source) {
return new ByteArrayInputStream(source.toByteArray());
}
private static ByteArrayOutputStream convertPDFToByteArrayOutputStream(String FilePath) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(new File(FilePath));
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
please answer my question

Value < of type java.lang.String cannot be converted to JSONArray In Android

I'm trying to upload the image in Samsung j7 camera. I get some server response with </div> tag.
How can I resolve this error and what is the way to get the image from the response?
Error Image Form Android Server Response
My code
protected void Upload_Server() {
// TODO Auto-generated method stub
String urlServer = null;
System.out.println("After call progress");
try{
Log.e("Image Upload", "Inside Upload");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = imagepath;
// String pathToOurFile1 = imagepathcam;
System.out.println("Before Image Upload" + imagepath);
if(Videoboolean){
urlServer = Constants.IMAGEVIDEOURL+"videopostUpload/";
}else {
urlServer = Constants.IMAGEVIDEOURL+"imagepostUpload/";
}
System.out.println("URL SETVER" + urlServer);
System.out.println("After Image Upload" + imagepath);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
System.out.println("enter the file path in android"+pathToOurFile);
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
// FileInputStream fileInputStream1 = new FileInputStream(new File(pathToOurFile1));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
System.out.println("URL is "+url);
System.out.println("connection is "+connection);
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
System.out.println("enter the image upload response"+outputStream.getClass().getCanonicalName());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
System.out.println("image"+serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
DataInputStream inputStream1 = null;
inputStream1 = new DataInputStream (connection.getInputStream());
String str="";
String Str1_imageurl="";
while (( str = inputStream1.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
Str1_imageurl = str;
Log.e("Debug","Server Response String imageurl"+str);
}
inputStream1.close();
System.out.println("image url"+Str1_imageurl);
PostImVD = Str1_imageurl.trim();
JSONArray array = new JSONArray(PostImVD);
JSONObject jsonObj = array.getJSONObject(0);
if(Videoboolean){
ImageVideo = jsonObj.optString("video_name");
}else {
ImageVideo = jsonObj.optString("image_name");
}
System.out.println("Profile Picture Path" + PostImVD);
System.out.println("Profile Picture Path" + ImageVideo);
}
catch(Exception e){
e.printStackTrace();
}
};
1: Error Image Form Android Server Response
First, try to validate your JSON response in this page for example:
https://jsonlint.com/
If your JSON is correct, then determine if is an array or an object, depends of that use the correct parsing :
If it's an array:
JSONArray array = new JSONArray(your_string_json);
If it's an object
JSONObject object = new JSONObject(your_string_json);

XMLHttpRequest js --> java --> js

i'm using XMLHttpRequest to send a variable from the js file to java file in the same project.
My problem and my question is: how i know my URL ?
Here is my code from js file
xhttp = new XMLHttpRequest();
var handlerFunction = getReadyStateHandler(xhttp, getValue);
xhttp.onreadystatechange = handlerFunction;
xhttp.open("POST",/* Location of my java file */,true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send(identMsg);
function getValue (body) {
var valueBody = body.getElementByTagName("body")[0];
}
function getReadyStateHandler(xhttp, responseXmlHandler) {
return function(){
if (xhttp.readyState == 4) {
if(xhttp.status == 200) {
responseXmlHandler(xhttp.responseXML);
} else {alert("Http error: " +xhttp.status);}
}
}
}
and the java code
public void doPost (HttpServletRequest xhttp, HttpServletResponse res) throws IOException {
String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = xhttp.getInputStream();
if (inputStream != null) {
bufferedReader = xhttp.getReader();
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer,0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch(IOException ex) {
throw ex;
} finally {
if(bufferedReader != null) {
try {
bufferedReader.close();
}catch (IOException ex2){
throw ex2;
}
}
}
body = stringBuilder.toString();
res.setContentType("application/xml");
res.getWriter().write(body);
}
what is missing?
EDIT: I need to get URL in the js side.
You can have the URL in js with document.location.href

The SmartSource Data collector JavaScript Tag, could be inserted from Java?

I'm totally new in Webtrends, I have read that The SmartSource Data collector JavaScript Tag, could be inserted from Java or HTML. does anyone know how to inser it from Java, I found the below class, is this class does the job? please provide some samples. Thanks in advance
public class DC {
public DC() {
super();
}
public String post_url(String connUrl, Map<String, String> bodyref) {
String response = "";
String responseCode = "";
try {
HttpURLConnection conn = null;
// construct data
String data = "";
Iterator<String> i = bodyref.keySet().iterator();
boolean ampersand = false;
while (i.hasNext()) {
if (ampersand) {
data += "&";
} else {
ampersand = true;
}
String b = i.next();
data += b + "=" + bodyref.get(b);
}
System.out.println();
System.out.println("[Request]");
System.out.println("(Url)");
System.out.println(connUrl);
System.out.println("(Body)");
System.out.println(data);
// send data
URL url = new URL(connUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
try {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
rd.close();
} catch (IOException e1) {
if (conn != null) {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
}
}
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.printf("%s %s\n", conn.getResponseCode(), conn.getResponseMessage());
System.out.println("(Message)");
System.out.println(conn.getResponseMessage());
System.out.println("(Body)");
System.out.println(response);
System.out.flush();
wr.close();
} catch (Exception e) {
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.println(e.toString());
System.out.println("(Message)");
System.out.println(e.getMessage());
System.out.flush();
}
return response;
}
public static void main(String[] args) {
DC dc = new DC();
// customer-specific DCSID
String dcsid = "dcslbiart00000gwngvpqkrcn_2u3z";
// base portion of DC API url
String base_url = "http://dc.webtrends.com/v1/" + dcsid;
// post body
Map<String, String> body1 = new HashMap();
// post query string
String querystring = "";
// compose urls
String id_url = base_url + "/ids.svc" + querystring;
String event_url = base_url + "/events.svc" + querystring;
// get visitor identifier
String id = dc.post_url(id_url, body1);
// post body
Map<String, String> body = new HashMap();
// initialize post body
body.put("dcsuri", "/MyJavaTest");
body.put("dcssip", "localhost");
body.put("WT.ti", "MyJavaTest");
body.put("WT.co_f", id);
body.put("dcsverbose", "true");
// submit event data
dc.post_url(event_url, body);
}

Categories

Resources