Asp.Net Mvc Load Image (img src) from Byte[] in javascript - javascript

I'm developing an application with ASP.Net Mvc4, Razor and javscript/Jquery.
I need to display images that are stored on a remote server, these images will fall within a component "slider".
I recover the address remote of the images and these store them in a List of byte[] from controller with json.
The Class ByteImages:
public class ByteImagenes {
public byte[] byimagen { get; set; }
public ByteImagenes(byte[] byImagen) {
byimagen = byImagen;
}
}
The Action Controller:
public JsonResult AlbumFoto(string Directorio){
var Lista = Galeria(true, Directorio);
return Json(new { Fotos = Lista });
}
private List<ByteImagenes> Galeria(bool Remoto, string Directorio){
string path = string.Empty;
DirectoryInfo dir = null;
List<ByteImagenes> flistImagenes = new List<ByteImagenes>();
if (!Remoto){
path = "/" + Directorio + "/";
dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + Directorio);
}
else {
path = Directorio;
dir = new DirectoryInfo(Directorio);
}
FileInfo[] fileList = dir.GetFiles("*.*", SearchOption.AllDirectories);
var fileQuery = from file in fileList
where ((file.Extension == ".jpg") ||
(file.Extension == ".png") ||
(file.Extension == ".gif") ||
(file.Extension == ".jpeg"))
orderby file.Name
select file;
foreach (var file in fileQuery){
var b = System.IO.File.ReadAllBytes(path + file.Name);
flistImagenes.Add(new ByteImagenes(b));
}
return flistImagenes;
}
In the View, I'm creating my gallery pictures in a function javascript.
In this function javascript I can't show the images.
function javascript:
function CrearGaleria(data) {
var elem;
$.each(data.Fotos, function (key, val) {
var _ParamImp = val.byimagen;
var link2 = '#Html.Raw("data:image;base64,#System.Convert.ToBase64String(Param)")';
link2 = link2.replace("Param", _ParamImp);
alert(link2);
elem = "<li><a><img src=" + link2 + " /></a></li>";
$("#ulImages").append(elem);
})
iniciarEfecto();
}
the alert(link2)this show me:
I can't load the image in src from array byte how I can resolve this problem?
EDIT I can resolve this problem...
I change my class before byte[] now string
public class Imagenes
{
public string imagen { get; set; }
public Imagenes(string sImagen)
{
imagen = sImagen;
}
}
and when load the values I change in private List Galeria in foreach Convert.ToBase64String
foreach (var file in fileQuery)
{
var b = System.IO.File.ReadAllBytes(path + file.Name);
listImagenes.Add(new Imagenes(Convert.ToBase64String(b)));
}
return listImagenes;
and in javascript in the view:
function CrearGaleria(data) {
var elem;
$.each(data.Fotos, function (key, val) {
elem = '<li><a><img src="data:image;base64,' + val.imagen + '"/></a></li>';
$("#ulImages").append(elem);
})
iniciarEfecto();
}
Now I can show the images. :-)

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 save records after importing Excel Sheet into ASP.NET Core Razor pages

Im trying tofind a way on how I can save the uploaded excell sheet to my database Ms SQL server.
I have the following:
Model
public class ImportDocs
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
}
HTML and JavaScript for viewing the records
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<input type="file" id="fUpload" name="files" class="form-control" />
</div>
<div class="col-md-8">
<input type="button" id="btnUpload" value="Upload" />
</div>
</div>
<br />
<div id="dvData"></div>
<br />
<div class="col-md-8">
<input type="button" id="btnSave" value="Save To Database" />
</div>
JavaScript
#Html.AntiForgeryToken()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnUpload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fUpload').val();
if (filename.length == 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fUpload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/ImportExcelFiles/Index?handler=Import",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
$('#dvData').html(response);
}
},
error: function (e) {
$('#dvData').html(e.responseText);
}
});
})
});
C# Code
private IHostingEnvironment _hostingEnvironment;
public IndexModel(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult OnPostImport()
{
IFormFile file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
StringBuilder sb = new StringBuilder();
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
ISheet sheet;
string fullPath = Path.Combine(newPath, file.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
stream.Position = 0;
if (sFileExtension == ".xls")
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
IRow headerRow = sheet.GetRow(0); //Get Header Row
int cellCount = headerRow.LastCellNum;
sb.Append("<table class='table'><tr>");
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
sb.Append("<th>" + cell.ToString() + "</th>");
}
sb.Append("</tr>");
sb.AppendLine("<tr>");
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
}
sb.Append("</table>");
}
}
return this.Content(sb.ToString());
}
}
How can I archieve this
You're almost there. What you need is to inspect the excel with Reflection and construct a list of ImportDocs, so that we can save the IList<ImportDocs> into database.
The process on server side can be divided into 4 parts :
create an instance of ISheet using current request
create a list of ImportDocs (we'll name it as 'records') instance using the sheet
save the list of records to database
build a html <table>...</table> for client displaying
Here's the structure of page model :
private IHostingEnvironment _hostingEnvironment; // injected by DI
private AppDbContext _dbContext; // injected by DI
public IActionResult OnPostSave(){
var sheet = this.ParseSheetFromRequest(false);
var records = this.ParseDocsFromSheet(sheet);
var sb = this.BuildTableHtml(records);
// typically, we'll use Database to generate the Id
// as we cannot trust user
foreach (var record in records) {
record.Id = default(int);
}
this._dbContext.ImportDocs.AddRange(records);
this._dbContext.SaveChanges();
return this.Content(sb==null?"":sb.ToString());
}
public IActionResult OnPostImport(){
var sheet = this.ParseSheetFromRequest(true);
var records = this.ParseDocsFromSheet(sheet);
var sb = this.BuildTableHtml(records);
return this.Content(sb==null?"":sb.ToString());
}
private ISheet ParseSheetFromRequest(bool saveFile) {
// ...
}
private List<ImportDocs> ParseDocsFromSheet(ISheet sheet){
// ...
}
private StringBuilder BuildTableHtml<T>(IList<T> records){
// ...
}
Here the ParseSheetFromRequest() is a helper method used to create a new ISheet from current request, I simply copy your code:
private ISheet ParseSheetFromRequest(bool saveFile) {
ISheet sheet= null;
IFormFile file = Request.Form.Files[0];
if (file.Length ==0 ) {
return sheet;
}
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
var stream = file.OpenReadStream();
if (sFileExtension == ".xls") {
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else {
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
var records = this.ParseDocsFromSheet(sheet);
// if need to save the file
if (saveFile) {
stream = file.OpenReadStream();
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath)) {
Directory.CreateDirectory(newPath);
}
string fullPath = Path.Combine(newPath, file.FileName);
using (var fileStream= new FileStream(fullPath, FileMode.Create)) {
file.CopyTo(fileStream);
}
}
return sheet;
}
And the ParseDocsFromSheet() is another helper method used to parse ImportDocs from sheet. It uses Reflection to inspect the field name and then construct a new strongly-typed instance at RunTime :
private List<ImportDocs> ParseDocsFromSheet(ISheet sheet){
IRow headerRow = sheet.GetRow(0); //Get Header Row
int cellCount = headerRow.LastCellNum;
// ["Id","LastName","","UserName","","Name"]
var headerNames= new List<string>();
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) {
headerNames.Add(""); // add empty string if cell is empty
}else{
headerNames.Add( cell.ToString());
}
}
var records= new List<ImportDocs>();
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
var record = new ImportDocs();
var type = typeof(ImportDocs);
for (int j = 0 ; j < cellCount; j++)
{
if (row.GetCell(j) != null){
var field = row.GetCell(j).ToString();
var fieldName = headerNames[j];
if(String.IsNullOrWhiteSpace(fieldName)){
throw new Exception($"There's a value in Cell({i},{j}) but has no header !");
}
var pi = type.GetProperty(fieldName);
// for Id column : a int type
if(pi.PropertyType.IsAssignableFrom(typeof(Int32))){
pi.SetValue(record,Convert.ToInt32(field));
}
// for other colun : string
else{
pi.SetValue(record,field);
}
}
}
records.Add(record);
}
return records;
}
Finally, to build the <table>, we can create a reusable method :
private StringBuilder BuildTableHtml<T>(IList<T> records)
where T: class
{
var type = typeof(T);
var pis = type.GetProperties();
var sb = new StringBuilder();
sb.Append("<table class='table'><tr>");
foreach(var pi in pis){
sb.Append("<th>" + pi.Name + "</th>");
}
sb.Append("</tr>");
foreach (var record in records) //Read Excel File
{
sb.AppendLine("<tr>");
foreach(var pi in pis){
sb.Append("<td>" + pi.GetValue(record) + "</td>");
}
sb.AppendLine("<tr>");
}
sb.Append("</table>");
return sb;
}
Test case:

Jquery progress bar while uploading record into database in java

I have thousands of record which are stored in a excel sheet and I need to upload those records into database, And currently I am using Spring controller class for upload, And inside my class I use simple BufferedOutputStream and FileReader classes, So my requirement is I need to show a Jquery progress-bar including percentages while uploading my data into database.
Link here.
My sample code.
String rootPath = request.getSession().getServletContext().getRealPath("/");
File dir = new File(rootPath + File.separator + "uploadedfile");
if (!dir.exists()) {
dir.mkdirs();
}
File serverFile = new File(dir.getAbsolutePath() + File.separator + form.getEmpFile().getOriginalFilename());
try {
try (InputStream is = form.getEmpFile().getInputStream();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
int i;
//write file to server
while ((i = is.read()) != -1) {
stream.write(i);
}
stream.flush();
}
}
catch (IOException e) {
model.addAttribute("msg", "failed to process file because : " + e.getMessage());
}
String[] nextLine;
try (FileReader fileReader = new FileReader(serverFile); CSVReader reader = new CSVReader(fileReader, ';', '\'', 1);) {
while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i < nextLine.length; i++) {
nextLine[i] = nextLine[i].trim();
if (!nextLine[i].equals("")) {
String[] data = nextLine[i].split(",");
Maybe this can help:
1- Controller side :
public class ExtractController {
********
// I created a global variable here
int percentage = 0;
Workbook workbook;
#RequestMapping(value ="/uploadExcel", method = RequestMethod.POST)
public #ResponseBody String uploadExcel(Model model, #RequestParam("excelfile") MultipartFile excelfile,
HttpServletResponse response) {
**********
try {
int i = 0;
*********
while (i <= worksheet.getLastRowNum()) {
percentage = Math.round(((i * 100) / worksheet.getLastRowNum()));
Row row = worksheet.getRow(i++);
}
*********
}catch (Exception e) {
e.printStackTrace();
}
return "extract";
}
#RequestMapping(value = "/getpercent", method = RequestMethod.GET)
public #ResponseBody String getPerc(#RequestParam("param") String param) {
************
// you return the value of the global variable when the action is called
return percrentage;
}
}
1- JavaScript side :
$.ajax({
url : 'uploadExcel',
type : 'POST',
data : new FormData(this),
beforeSend : function() {
$('#valid').attr("disabled", true);
// I call my loop function
loop();
},
success : function(data) {
$('#valid').attr("disabled", false);
}
});
function loop() {
$.ajax({
url : 'getpercent',
type : 'GET',
success : function(response) {
count = response;
// this function updates my progress bar with the new value
change(count);
*********
}
});
var time = 2000;
if(count < 100){
setTimeout(loop, time);
}
}
;

Multiple Image File Upload with Captions

I managed to get the captions by foreach loop but now I'm facing a new problem.
I get duplicates in my database because of the nested loop, please check the code below.
JavaScript
window.onload = function () {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("galleryFilesAdd");
filesInput.addEventListener("change", function (event) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail img-responsive' alt='" + picFile.name + "' + height='220' width='300'; src='" + picFile.result + "'" +
"title='" + picFile.name + "'/><button type='button' class='delete btn btn-default' class='remove_pic'> <span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button><input type='text' id ='imagecaption[]' name='imagecaption[]' class='form-control' placeholder='Add Image Caption'>"
output.insertBefore(div, null);
div.children[1].addEventListener("click", function (event) {
div.parentNode.removeChild(div);
});
});
//Read the image
picReader.readAsDataURL(file);
}
});
}
else {
console.log("Your browser does not support File API");
}
}
Controller
public async Task<ActionResult> AddHotel(HotelViewModels.AddHotel viewModel, IEnumerable<HttpPostedFileBase> galleryFilesAdd)
{
try
{
if (ModelState.IsValid)
{
foreach (var files in galleryFilesAdd)
{
var fileName = Guid.NewGuid().ToString("N");
var extension = Path.GetExtension(files.FileName).ToLower();
string thumbpath, imagepath = "";
using (var img = Image.FromStream(files.InputStream))
{
foreach (var caption in viewModel.imagecaption)
{
var galleryImg = new hotel_gallery_image
{
hotel_id = hotel.id,
thumbPath = String.Format("/Resources/Images/Hotel/GalleryThumb/{0}{1}", fileName, extension),
imagePath = String.Format("/Resources/Images/Hotel/Gallery/{0}{1}", fileName, extension),
entry_datetime = DateTime.Now,
guid = Guid.NewGuid().ToString("N"),
enabled = true,
image_caption = caption
};
db.hotel_gallery_image.Add(galleryImg);
}
}
}
await db.SaveChangesAsync();
return RedirectToAction("Index", "Hotel");
}
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
throw new DbEntityValidationException(errorMessages);
}
viewModel.Country = await db.countries.ToListAsync();
return View(viewModel);
}
and viewModel
public string[] imagecaption { get; set; }
Inserted data into database
I think the problem is in your
image_caption = viewModel.imagecaption
because you iterate through var files in galleryFilesAddyou use the reference to the same image_caption from viewModel on each iteration, so you need to filter your image_caption depending on another data (fileName or another data which you viewmodel contains).
UPDATE
Ideally if you have same properties in your ViewModel and files(filename for example), then you could do something like thatimage_caption = viewModel.FirstOrDefault(x=>x.Filename == filename).imagecaption
In order to be more specific would be helpful if you provide code for your Viemodel and galleryFilesAdd classes.
UPDATE 2
In your case 2nd foreach you iterate through whole collection of imagecaption array, on each iteration through galleryFilesAdd collection, which cause double data in you database.
If you can take your captions sequentially for the 1st file take the 1st element from imagecaption array and so on then you can use code like this:
if (ModelState.IsValid)
{
int index = 0;
foreach (var files in galleryFilesAdd)
{
var fileName = Guid.NewGuid().ToString("N");
var extension = Path.GetExtension(files.FileName).ToLower();
string thumbpath, imagepath = "";
using (var img = Image.FromStream(files.InputStream))
{
if(index < viewModel.imagecaption.Length){
var galleryImg = new hotel_gallery_image
{
hotel_id = hotel.id,
thumbPath = String.Format("/Resources/Images/Hotel/GalleryThumb/{0}{1}", fileName, extension),
imagePath = String.Format("/Resources/Images/Hotel/Gallery/{0}{1}", fileName, extension),
entry_datetime = DateTime.Now,
guid = Guid.NewGuid().ToString("N"),
enabled = true,
image_caption = viewModel.imagecaption[index]
};
db.hotel_gallery_image.Add(galleryImg);
index++;
}
}
}

Getting web response when button clicked in BlackBerry

I have loaded a web page in BB as follow
//RegBrowserFieldConfig extends BrowserFieldConfig
RegBrowserFieldConfig regBrowserFieldConfig = new RegBrowserFieldConfig();
//RegBrowserFieldListener extends BrowserFieldListener
RegBrowserFieldListener regBrowserFieldListener = new RegBrowserFieldListener();
BrowserField registrationBrowserField = new BrowserField(regBrowserFieldConfig);
registrationBrowserField.addListener(regBrowserFieldListener);
add(registrationBrowserField);
registrationBrowserField.requestContent("http://myurl.com/");
That web page loads fine. There is a submit button in that web page which call onsubmit in the form element in HTML. That is calling to a JavaScript function. With in that function there are some other URL that will fire according to the requirements.
What I need is to get the response of those URL calls. How can I do that?
I tried this way..
BrowserFieldListener list = new BrowserFieldListener() {
public void documentLoaded(BrowserField browserField,
Document document) throws Exception {
String url = document.getBaseURI(); //u can get the current url here... u can use ur logic to get the url after clicking the submit button
Serverconnection(url);//from this methode u can get the response
}
};
browserField.addListener(list);
Serverconnection..
public String Serverconnection(String url) {
String line = "";
// if (DeviceInfo.isSimulator()) {
// url = url + ";deviceSide=true";
// } else {
// url = url + ";deviceSide=true";
// }
url = url + getConnectionString();
try {
HttpConnection s = (HttpConnection) Connector.open(url);
s.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
s.setRequestProperty(
"Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
s.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"UTF-8");
s.setRequestMethod(HttpConnection.GET);
InputStream input = s.openInputStream();
byte[] data = new byte[10240];
int len = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
line = raw.toString();
input.close();
s.close();
} catch (Exception e) {
System.out.println("response--- excep" + line + e.getMessage());
}
return line;
}
EDIT..
private static String getConnectionString() {
String connectionString = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = "?;interface=wifi";
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = "?;&deviceside=false";
} else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
connectionString = "?;deviceside=true";
} else {
connectionString = "?;deviceside=false?;connectionUID="
+ carrierUid + "?;ConnectionType=mds-public";
}
} else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
}
return connectionString;
}
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}

Categories