Is there any way that I can read a .json file (located in server) from a javascript http adapter?
I tried a lot of methods described in the internet but they don't seem to work because they are made for browser javascript (I get errors like XMLHttpRequest is not defined or activeObject is not defined).
for example, I used this but it doesn't work:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
return allText;
}
}
}
rawFile.send(null);
}
Is there any way that I could do this without using java?
You can read a file with Javascript as shown below.
function readFile(filename) {
var content = "";
var fileReader = new java.io.FileReader(filename);
var bufferedReader = new java.io.BufferedReader(fileReader);
var line;
while((line = bufferedReader.readLine()) != null) {
content += line;
}
bufferedReader.close();
return content;
}
function test() {
var file = 'yourfilename.json';
var fileContents;
try {
fileContents = JSON.parse(readFile(file));
} catch(ex) {
// handle error
}
return {
fileContents: fileContents
};
}
For those interested in using Java.
One thing you can do is create a Javascript adapter which will use Java code. It is pretty simple to set up.
First create a Javascript adapter.
Then create a Java class under the server/lib folder. I created the class ReadJSON.java under the package com.sample.customcode.
Inside the ReadJSON.java
public class ReadJSON {
public static String readJSON() throws IOException {
//Open File
File file = new File("file.txt");
BufferedReader reader = null;
try {
//Create the file reader
reader = new BufferedReader(new FileReader(file));
String text = null;
//read file
while ((text = reader.readLine()) != null) {}
} finally {
try {
//Close the stream
reader.close();
}
}
return "the text from file";
}
}
Inside your javascript adapter you can use Java methods like below:
function readJOSN() {
var JSONfromServer = com.sample.customcode.ReadJSON.readJSON();
return {
result: JSONfromServer
};
}
Hope this helps.
Related
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.
I am trying to POST a .tgz file using XHR as part of a file upload.
The file itself is valid and I have tested it via manual upload. The issue I am having (I think) is when I encode the file into base64 and upload it, it is being corrupted and not not being picked up as valid.
The file itself is a plugin module for Atmail, which I have tested manually like I said.
This is my upload function with the base64 truncated.
I am encoding the target file initially with:
cat myfile.tgz | base64 > base64_file
and shortening/removing new lines with:
sed ':a;N;$!ba;s/\n/ /g' plugin.base64 > t
My question is, is this the correct way to encode a compressed file for use in my POST request? And if so what is wrong with my implementation?
function uploadPlugin()
{
var uri = "/index.php/admin/plugins/preinstall";
var name = "newPlugin";
filename = "RCE.tgz";
// Comments and extra lines removed to reduce payload size
// Remove new lines: sed ':a;N;$!ba;s/\n/ /g' plugin.base64 > t
var content = "H4sIAAAAAAAAA+0aa2/bOLJfk1/BFYJaLvyIs0m6TZpss30Awe22vabXA65XqLREx2xkSSWppNlu ...";
var formData = new FormData();
var blob = new Blob([atob(content)],
{
type: "application/x-gtar-compressed"
}
)
formData.append(name, blob, filename);
var request = new XMLHttpRequest();
request.open("POST", uri);
request.send(formData);
}
This is the ATMail plugin class I am using.
<?php
class Atmail_Test_Plugin extends Atmail_Controller_Plugin
{
protected $_pluginFullName = 'rce';
protected $_pluginModule = 'mail';
private $_loginPage = false;
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$request = $this->getRequest();
if (($request->getControllerName() == 'index' && $request->getActionName() == 'index') ||
($request->getControllerName() == 'auth' && $request->getActionName() == 'logout')) {
$this->_loginPage = true;
}
}
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
if ($this->_loginPage) {
$page = $this->getResponse()->getBody();
$page = str_replace("</body>", "<!-- plugins working -->\n</body>", $page);
$this->getResponse()->setBody($page);
}
}
public function setup()
{
$db = zend_Registry::get("dbAdapter");
$db->query("drop table if exists `TestPluginSettings`");
$db->query("create table `TestPluginSettings` (`id` int auto_increment primary key, `keyName` varchar(12), `keyValue` text, index `keyName` (`keyName`))");
}
public function setViewRenderScript()
{
//return "/path/to/nothing.phtml";
}
public function setViewRenderAction()
{
}
}
I eventually found out what was going wrong. I was trying to post binary data incorrectly. Below is the working solution.
function uploadPlugin()
{
var uri = "/index.php/admin/plugins/preinstall";
var name = "newPlugin";
filename = "Upload.tgz";
var body = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xed\x1a\x6b\x6f\xdb" +
"\x38\xb2\x5f\x93\x5f\xc1\x15\x82\x5a\x2e\xfc\x88\xb3\x49\xba" +
"..." +
"...";
var formData = new FormData();
var payload = new Uint8Array(body.length);
for (var i = 0; i < payload.length; i++)
{
payload[i] = body.charCodeAt(i);
}
var blob = new Blob([payload])
formData.append(name, blob, filename);
var xhr = new XMLHttpRequest();
xhr.open("POST", uri);
xhr.send(formData);
}
I have a FileUpload control where I upload PDF files and they get saved to a folder, the file path gets saved to the database.
The problem is when I upload a file which contains parenthesis () as part of the file name, it returns undefined. This only happens if the file name has parenthesis () , if it does not have parenthesis () it uploads fine.
This is my code
var filePaths;
function UploadFile() {
var fileUpload = document.getElementById("fuPDFupload");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.pdf)$");
if (regex.test(fileUpload.value.toLowerCase())) {
//Check whether HTML5 is supported.
if (typeof (fileUpload.files) != "undefined") {
//Initiate the FileReader object.
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
var fileUpload = $("#fuPDFupload").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
url: "FileUploadHandler.ashx",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (result) {
filePaths = result;
//Save to DB
UpdateSchedule();
},
error: function (err) {
}
});
return true;
};
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
return false;
}
}
FileUploadHandler Code:
public class FileUploadHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
string filePaths = Guid.NewGuid().ToString() + ".pdf";
HttpPostedFile file = context.Request.Files[0];
string path = context.Server.MapPath("~/QfrencyInvoices/" + filePaths);
file.SaveAs(path);
context.Response.ContentType = "text/plain";
context.Response.Write(filePaths);
}
}
public bool IsReusable {
get {
return false;
}
}
}
I believe that the problem might be happening because the Regex expression is incorrect but I have not been able to fix it.
Please assist me how I can upload files that have parenthesis () as part of the file name. Thank you.
Just leave next regex new RegExp("(\.(jpg|png|pdf)$", "i");. It checks that filename has extension jpg, png or pdf. Text case does not matter so "i" was added as the second parameter.
You can learn regular expressions on https://regexone.com/
So my title might not explain things all to well, so I'll explain better, I am working on this extension for chrome that grabs synonyms from a dat file I found on the web from someone at MIT. I've gotten most of my idea written in Java (my native language), here it is so you can see what I'm trying to do:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
public class Grabber {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
URL mit = new URL(
"http://mit.edu/~mkgray/jik/sipbsrc/src/thesaurus/old-thesaurus/lib/thesaurus.dat");
BufferedReader in = new BufferedReader(new InputStreamReader(
mit.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.startsWith("spoken")) {
ArrayList<String> list = new ArrayList<String>();
String[] synonyms = inputLine.substring("spoken".length())
.split(" ");
for (String toPrint : synonyms) {
if (toPrint.length() > 0) {
list.add(toPrint.trim());
}
}
for (String toPrint : list) {
System.out.println(toPrint);
}
}
}
in.close();
}
}
Now, with my 'Codecademy' knowledge of the language, I don't know about all the library's and such included in Chrome's JavaScript API. We're should I start looking to complete this task? Oh, I also need to figure out how to make array's in JavaScript, act like the collection I wrote above.
Here's an example:
var xhr = new XMLHttpRequest(); // Use XMLHttpRequest to fetch resources from the Web
xhr.open("GET", // HTTP GET method
"http://mit.edu/~mkgray/jik/sipbsrc/src/thesaurus/old-thesaurus/lib/thesaurus.dat",
true // asynchronous
);
xhr.onreadystatechange = (function()
{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) // success
{
// data fetched in xhr.responseText, now parse it
var inputLines = xhr.responseText.split(/\r|\n|\r\n/); //Split them into lines
/* A quick and brief alternative to
while ((inputLine = in.readLine()) != null) {
if (inputLine.startsWith("spoken")) {
...
}
} */
inputLines.filter(function(inputLine)
{
// You can also use
// return inputLine.substr(0, 6) == "spoken";
// if you are not familiar with regular expressions.
return inputLine.match(/^spoken/);
}).forEach(inputLine)
{
var list = [];
var synonyms = inputLine.substring("spoken".length).split(" ");
synonyms.fonEach(function(toPrint)
{
if(toPrint.length > 0)
list.push(toPrint.replace(/^\s+|\s+$/g, ''));
//toPrint.replace(/^\s+|\s+$/g, '') is similar to toPrint.trim() in Java
//list.push(...) is used to add a new element in the array list.
});
list.forEach(function(toPrint)
{
// Where do you want to put your output?
});
});
}
});
xhr.send(); // Send the request and fetch the data.
I am writing a Firefox extension. Right now I need to create a local copy of a XML file and I am almost successful. A File is read and a new one is created but this one is empty. Is there a special method for XML files or why does it not work?
Here are the functions:
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send("");
return xhttp.responseXML;
}
and
function localcopy() {
var url = content.document.location.href;
var prefManagerr = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.foafnet.");
var prefStringx;
if (prefManagerr.prefHasUserValue("stringpref1")) {
prefStringx = prefManagerr.getCharPref("stringpref1");
} else {
// Preference is default value so use that
prefStringx = "0"
}
if (prefStringx == url) {
xml = loadXMLDoc(prefStringx);
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("TmpD", Components.interfaces.nsIFile);
file.append("profiletemp.xml");
file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
// do whatever you need to the created file
alert(file.path);
//
var stream = Components.classes["#mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate
stream.write(xml, xml.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
}
}
The beginning of the second function just declares, that a local copy is only to be made if the called website hast the same url as a url defined in the preferences of the extension. this part works just fine.
The first parameter to nsIOutputStream.write() has to be a string - you are giving it an XML document instead. You can use XMLSerializer to convert XML into text and to write it to a stream directly:
new XMLSerializer().serializeToStream(xml, stream, "utf-8");