I want print receipt in client side without print dialog box, i am using mvc this is my solution to achieve my problem.
EPSON printer was installed in my system.This solution is working when host in my local iis but its not work when host in server and accessing from my local system getting "An error occurred while processing your request" error. In server no printer is installed.
$.ajax({
type: "POST",
url: '../Service/print',
cache: false,
data: { iprintData: printData, iprinterName: sPrinterName },
success: function (data) {
// alert('print Send Successfully');
},
error: function (ex) {
alert(ex.responseText);
// alert('error while Seding print');
}
});
this is my code in controller
public JsonResult print(string iprintData, string iprinterName)
{
Boolean bflag = false;
System.Web.HttpContext.Current.Session["_printData"] = iprintData;
PrintDocument printDocument = new PrintDocument();
printDocument.PrintController = new StandardPrintController();
printDocument.PrintPage += PrintDocumentOnPrintPage;
printDocument.PrinterSettings.PrinterName = iprinterName;
//printFont = new System.Drawing.Font("Arial", 10);
printDocument.Print();
bflag = true;
return Json(bflag, JsonRequestBehavior.AllowGet);
}
public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_height, new_width);
Graphics g = Graphics.FromImage((Image)new_image);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
private void PrintDocumentOnPrintPage(object sender, PrintPageEventArgs e)
{
string printstring = System.Web.HttpContext.Current.Session["_printData"].ToString();
string path = HttpContext.Server.MapPath("~/content/Images/logo.png");
System.Drawing.Image img = Image.FromFile(path);
//img = resizeImage(img, 80, 60);
e.Graphics.DrawImage(img, 6, 100);
e.Graphics.DrawString(printstring, new System.Drawing.Font("ronnia", 9), Brushes.Black, 10, 150);
}
can any one help me from this ?
first you have to write windows service that contain HttpListener.
write your printing code inside the service
Install the service in client machine
call that service using ajax like below.
function PrintReceipt() {
var PrintData = JSON.parse($("#receiptData").html())
if (PrintData.length > 0) {
$.ajax({
type: "POST",
url: "http://localhost:41963/printOrder",
data: JSON.stringify({ "PrintData": PrintData }), //reciept data
crossDomain: true,
success: function (response) {
},
error: function () {
}
});
}
}
set System.Drawing.dll property
Copy Local=true
Related
I have a program (Spring Boot) which is using REST service to upload files to the server or any other given location. But when I use the same service below error happened and below is the problem.
I am getting 400() error without any description when uploading a file via REST service. This application is Spring boot application which use java-script front-end to upload and download files via implemented rest service.
Help to resolve this. your help is appreciated. Thanks.
error is :
below is the code:
JS:
document.getElementById('import2').onclick = function () {
var files = document.getElementById('selectFiles').files;
console.log(files);
if (files.length <= 0) {
return false;
}
//serverUploaded = true;
var form_data = new FormData(files.item(0));
//from new NLP
$.ajax({
type: "POST",
url: "http://localhost:8080/gsta/upload",
processData: false,
contentType: false,
async: false,
cache: false,
data: form_data,
success: function (result) {
//alert(JSON.stringify(result));
//$("#out_lexalytics").html(JSON.stringify(result));
if (result) {
if(result.statusCode == 200)
{
serverUploaded = true;
}
}
}
});
}
REST service:
#PostMapping("/upload")
// If not #RestController, uncomment this
#ResponseBody
public ResponseEntity<?> uploadFile(#RequestParam("data") MultipartFile uploadfile) {
logger.debug("Single file upload!");
if (uploadfile != null && uploadfile.isEmpty()) {
return new ResponseEntity("please select a file!", HttpStatus.OK);
}
try {
saveUploadedFiles(Arrays.asList(uploadfile));
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
}
I created the same scenario in my local environment with postman like this;
Server side with one small change (#RequestMapping(value = "/upload", method = RequestMethod.POST));
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<?> uploadFile(#RequestParam("data") MultipartFile uploadfile) {
logger.debug("Single file upload!");
if (uploadfile != null && uploadfile.isEmpty()) {
return new ResponseEntity("please select a file!", HttpStatus.OK);
}
return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
}
It works.
My assumption: your method saveUploadedFiles throws an IOException.
As you are getting a 400 Bad Request as response, I Think you should debug your
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Block in order to find out what causes a IOException.
Hello Everyone I am using angularjs to send byte array on server side but I am not getting data on server side.
Here is my code.
$scope.Upload = function () {
var bytesToSend = [253, 0, 128, 1]
var send = new Uint8Array(bytesToSend)
var Upload = $.ajax({
type: 'POST',
url: "/UploadFile",
dataType: JSON,
contentType: false,
data: send,
success: function (send) {
toastr.success("Upload Successfully");
}
});
Upload.error(function () { console.log(bytesToSend+'gaurav') });
}
And here is my server side code
[HttpPost]
[Route("UploadFile")]
public bool UploadedFile(byte[] send)
{
return false;
//return await CenterGateWay.UpldFile(up);
}
}
I am not getting data in byte[] send it is showing null value.
please anyone help where I am wrong And I am getting data in console
here [253, 0, 128, 1].
Using firefox browser right now.
Please use following code to resolve your issue.
$scope.Upload = function () {
var bytesToSend = [253, 0, 128, 1];
var send = new Uint8Array(bytesToSend)
var Upload = $.ajax({
type: 'POST',
url: "/Home/UploadFile",
dataType: "JSON",
data: { send: btoa(String.fromCharCode.apply(null, send)) },
success: function (send) {
toastr.success("Upload Successfully");
}
});
Upload.error(function () { console.log(bytesToSend + 'gaurav') });
}
In Controller
[HttpPost]
[Route("UploadFile")]
public bool UploadedFile(string send)
{
return false;
//return await CenterGateWay.UpldFile(up);
}
Even I got help from this link Please refer it:-
I want to upload javascript fileor basically transmit a javascript file to post function, on client side I've used angularjs $http service to send data to client as shown below:
$http({
method: "POST",
url: "/api/fileupload",
data: JSON.stringify(scope.c.model),//scope.c.model is javascript File
contentType: "application/json"
}).then(successResponse => {
this.scope["text"] = "Succes...";
}, errorResponse=> {
this.scope["text"] = "Error...";
});
and here is web-api controller
public void Post(HttpPostedFile file)
{
//do stuff...
}
file is null but scope.c.model is filled with correct data. if I change the Type of data is transmitted to an array (for example), everything is fine..It seems that the post method does not recognize the file.
seocnd below way also does not work, file.count is zero.
public void Post()//HttpPostedFile file)
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
//do stuff...
}
}
Here is a solution for the problem..with code below I am totally able to save any file locally or on server.
client side
scope.c.model is the type of Javascript FILE API. behind the scene is the model which is like this ng-model = model , c is controller and becasue this code is in link function of my directive I can access the model trough scope.c.model . model here could be any name.
as I want to read the File I should use FileReader.
scope.$watch('c.model', () => {
if (scope.c.model != null) {
var reader = new FileReader();
reader.onload = () => {
var base64 = reader.result.split("base64,")[1];
var file =
{
content: base64,
name: scope.c.model.name,
type: scope.c.model.type,
size: scope.c.model.size
};
var t = file.content;
$http({
method: "POST",
url: "/api/fileupload",//web-api contorller
data: file,// scope.c.model is javascript File
contentType: "application/octet-stream"
}).then(successResponse => {
this.scope["text"] = "Succes...";
}, errorResponse=> {
this.scope["text"] = "Error...";
});
};
reader.readAsDataURL(scope.c.model);
}
});
server side
public class File
{
public string Content;
public string Name;
public string Type;
public string Size;
}
public class FileUploadController : ApiController
{
public void Post(File file)
{
var bytes = Convert.FromBase64String(file.Content);
using (var imageFile = new FileStream(#"C:\fileupload\"+file.Name + ".jpg", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
}
}
Becouse I have many dinamicly created data (in popover window) I need to create ann function like this:
function addOffer() {
var token = document.getElementsByName('_token')[0].value;
var s1 = $('.hstart').val();
var p1 = $('.spin').val();
$.ajax({
url: '/offers',
type: 'POST',
data: {
price: p1,
start: s1,
_token: token
},
});
};
Now I call this function with:
$('.addBid').click(function() {
addOffer();
});
and request is send to backend but then I get:
k.cors.a.crossDomain.send # jquery.js:8630
UPDATE:
In Laravel backend I have only:
public function store(Requests\OfferRequest $request)
{
$offer = new Offer($request->all());
Auth::user()->offer()->save($offer);
Alert::success('Offer is succesfully added!', 'Good job!')->persistent("Close");
return Redirect::back();
}
I have a Rest API:
[HttpPost]
[Route("Services/Image/Upload")]
public string Upload([FromBody]GalleryItem galleryItem)
{
try
{
var appSettings = ConfigurationManager.AppSettings["GalleryPath"].ToString();
using (FileStream fs = new FileStream(appSettings + galleryItem.KeyCode + ".jpg", FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(galleryItem.Base64);
bw.Write(data);
bw.Close();
}
}
return "OK";
}
catch (Exception ex)
{
return ex.ToString();
}
}
and I call it from my Javascript client like:
var galleryItem = new Object();
galleryItem.Base64 = base64;
galleryItem.KeyCode = '1234';
url = "http://my domain name/api/Services/Image/Upload";
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(galleryItem),
contentType: 'application/json; charset=utf-8',
dataType: 'text/plain',
success: function (msg) {
alert('Image saved successfully !');
},
error: function (jqXHR, textStatus, err) {
$('#error').html('Error: ' + err);
}
});
my model:
public class GalleryItem
{
public string Base64 { get; set; }
public string KeyCode { get; set; }
}
I a testing this via a mobile device as I am taking image from camera to send up.
Nothing appears to happen? I just 'Error: error'?
thanks
ADDITIONAL:
After porting to a test script (wished I had done that sooner) I found the error is this:
net::ERR_NAME_NOT_RESOLVED
Though why I am unsure as I am calling another method from that api with no issues
Solved!
Thank God!
I changed the url to relative:
url = "/api/Services/Image/Upload";
without prefixing with domain name.
it must have got confused and thought it needed cors? (guess here)