XMLHttpRequest js --> java --> js - javascript

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

Related

Make Byte array To File for download Using ajax

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!

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

Intercept action form with method post webview android

I wanna intercept all of http request for adding header to my request and build response. I used all algorithm and libraries ( okHttp, HttpUrlConnection) but no hope :(
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String urlString = request.getUrl().toString();
if (Build.VERSION.SDK_INT >= 21) {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty(Constants.KEY_HEADER, Constants.VALUE_KEY_HEADER);
if (request.getMethod().equals("POST")) {
urlConnection = getPostData(urlConnection, request);
}
InputStream in;
int statusCode = urlConnection.getResponseCode();
if (statusCode == 400 || statusCode == 401 || statusCode == 404) {
in = urlConnection.getErrorStream();
} else {
in = urlConnection.getInputStream();
}
String typeMime = urlConnection.getHeaderField("Content-Type");
if (typeMime == null){
typeMime = "text/html";
}
if (urlString.equals("fontawesome-webfont.woff")) {
typeMime = "application/font-woff";
}
if (typeMime.contains("text/html")) {
typeMime = "text/html";
} else if (typeMime == null || typeMime.contains("application/font-woff")) {
typeMime = "application/font-woff";
}
return new WebResourceResponse(typeMime, "utf-8", in);
} catch (IOException ioe) {
Log.d(Constants.LOG_TAG, "IOException : " + ioe.getMessage());
return null;
}
} else {
return null;
}
private HttpURLConnection getPostData(HttpURLConnection urlConnection, WebResourceRequest request) throws IOException {
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
for (String key : request.getRequestHeaders().keySet()) {
String valueKey = request.getRequestHeaders().get(key);
Log.d("key is = ", "" + key + " and value = " + valueKey);
urlConnection.setRequestProperty(key, valueKey);
}
urlConnection.setRequestProperty(URLCache.KEY_X_CSRF_Token, URLCache.VALUE_X_CSRF_Token);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("signin[username]", "dfgdfg"));
params.add(new BasicNameValuePair("signin[password]", "dfgdfg"));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "utf-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
return urlConnection;
}
For "GET" Method its work fine but not method "POST" in forum action

How to Post images using XMLHttpRequest and ASP.net MVC

I am trying to upload multiple image with AngularJS. As i have to track the progress of each file i decide to use XMLHttpRequest to Post the image to ASP.net MVC controller. the js code is as follows
$scope.UploadImage=function()
{
var reqObj = new XMLHttpRequest();
//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false)
reqObj.addEventListener("load", uploadComplete, false)
reqObj.addEventListener("error", uploadFailed, false)
reqObj.addEventListener("abort", uploadCanceled, false)
for (var i = 0; i < $scope.fileList.length; i++)
{
var fileToUpload = $scope.fileList[i].file;
var fd = new FormData();
fd.append('file', fileToUpload);
reqObj.open("POST", "/WebDevelopment/SaveImage", false);
reqObj.setRequestHeader("Content-Type", "multipart/form-data");
reqObj.send(fd);
}
function uploadProgress(evt) {
$scope.uploadProgressCount = Math.round(evt.loaded * 100 / evt.total);
$scope.$apply();
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText)
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.")
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.")
}
}
I tried the following ASP.net MCV Controller to receive the file
public JsonResult SaveImage()
{
string path = "";
var httpRequest = System.Web.HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
// do something
}
}
the problem is i found httpRequest.Files.Count is zero all time. Why? i googling many time but do not understand what is going wrong. any one there to help me
I had problems with Request.Files but it helped me to take an approach, it might be useful for you as well
public class WebDevelopmentController : Controller
{
[HttpPost]
public JsonResult SaveImage()
{
var fileContents = new byte[Request.ContentLength];
Request.InputStream.Read(fileContents, 0, Request.ContentLength);
var filename = Request.Headers["X-File-Name"];
var fileType = Request.Headers["X-File-Type"];
var file = new UploadedFile() {
Filename = filename,
ContentType = fileType,
FileSize = fileContents != null ? fileContents.Length : 0,
Contents = fileContents
};
// save the file.
var saveToFileLoc = string.Format("{0}\\{1}",
Server.MapPath("/Content"),
file.Filename);
var fileStream = new FileStream(saveToFileLoc, FileMode.Create, FileAccess.ReadWrite);
fileStream.Write(file.Contents, 0, file.FileSize);
fileStream.Close();
return null;
}
public class UploadedFile
{
public int FileSize { get; set; }
public string Filename { get; set; }
public string ContentType { get; set; }
public byte[] Contents { get; set; }
}
}
And move your XHR object to the loop:
$scope.UploadImage = function() {
for (var i = 0; i < $scope.fileList.length; i++) {
var reqObj = new XMLHttpRequest();
//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false)
reqObj.addEventListener("load", uploadComplete, false)
reqObj.addEventListener("error", uploadFailed, false)
reqObj.addEventListener("abort", uploadCanceled, false)
var fileToUpload = $scope.fileList[i].file;
var fd = new FormData();
fd.append('file', fileToUpload);
reqObj.open("POST", "/WebDevelopment/SaveImage", false);
reqObj.setRequestHeader("Content-Type", "multipart/form-data");
reqObj.send(fd);
}
function uploadProgress(evt) {
$scope.uploadProgressCount = Math.round(evt.loaded * 100 / evt.total);
$scope.$apply();
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText)
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.")
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.")
}
}

Multiple Httppost connections?

How can I make multiple Httppost connections at the same time? I keep getting the following error:
05-05 19:28:08.920: E/AndroidRuntime(6983): Make sure to release the
connection before allocating another one.
My httppost code
HttpPost httpPost = new HttpPost("http://mydomain.com/api");
MultipartEntity mentity = new MultipartEntity();
mentity.addPart("token",token);
mentity.addPart("ts",ts);
httpPost.setEntity(mentity);
response = httpclient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
body = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
EntityUtils.consume(entity);
i have used like this and it is working.
public String reportCrime(String uploadFile, int userid, int crimetype,
String crimedetails, String lat, String longi, String reporteddate) {
String url;
MultipartEntity entity;
try {
url = String.format(Constant.SERVER_URL
+ "push_notification/reportCrime.php");
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//
File file = new File(uploadFile);
if (!file.equals("Image not Provided.")) {
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", uploadFile);
entity.addPart("image", foto);
}
} else {
FormBodyPart image = new FormBodyPart("image", new StringBody(
""));
entity.addPart(image);
}
FormBodyPart userId = new FormBodyPart("userId", new StringBody(
String.valueOf(userid)));
entity.addPart(userId);
FormBodyPart crimeType = new FormBodyPart("crimetype",
new StringBody(String.valueOf(crimetype)));
entity.addPart(crimeType);
FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
new StringBody(crimedetails));
entity.addPart(crimeDetails);
FormBodyPart latittude = new FormBodyPart("latittude",
new StringBody(lat));
entity.addPart(latittude);
FormBodyPart longitude = new FormBodyPart("longitude",
new StringBody(longi));
entity.addPart(longitude);
FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
new StringBody(reporteddate));
entity.addPart(reportedDate);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return "error";
}
HttpParams httpParams = new BasicHttpParams();
HttpContext httpContext = new BasicHttpContext();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
result = sb.toString();
} finally {
if (in != null)
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Categories

Resources