For one of the implementation, from Java code I am hitting labelary Rest service to convert ZPL formatted code to Image.
I am able to successfully fetch the response. But I am not able to convert the HttpResponse to image file.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/");
byte[] byteArray = Base64.decodeBase64(base64Val.getBytes());
String decodedString = new String(byteArray);
StringEntity requestEntity;
try {
requestEntity = new StringEntity(decodedString);
requestEntity.setContentType("application/x-www-form-urlencoded");
post.setEntity(requestEntity);
HttpResponse response = client.execute(post);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
#Need suggestions to convert BufferReader to Image
}
Post referring the suggested answer, code looks like:
HttpResponse response = client.execute(post);
InputStream inStream = response.getEntity().getContent();
String dataString = convertStreamToString(inStream);
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
File outputfile = new File("myImage.png");
ImageIO.write(image, "png", outputfile);
use this byte to image converter. past value in datastring and check whether you get the image.
Related
I am trying to store base64 encoded image to azure blob storage. PFB the code snippet for the same.
File is getting created but it is coming as broken image.
Code Snippet
String mimeType = extractMimeType(imageBase64Encoded).replace("image/", "");
String fileName = "image." + mimeType;
BlobContainerClient containerClient = new BlobContainerClientBuilder()
.connectionString(connectionString)
.containerName(containerName)
.buildClient();
BlobClient client = containerClient.getBlobClient(fileName);
String base64Data = imageBase64Encoded.split(",")[1];
byte[] base64DataBytes = base64Data.getBytes();
ByteArrayInputStream dataStream = new ByteArrayInputStream(base64DataBytes);
client.upload(dataStream, base64DataBytes.length);
You need to decode the base64 encoded string to byte[] and use that byte[] to store the image.
String mimeType = extractMimeType(imageBase64Encoded).replace("image/", "");
String fileName = "image." + mimeType;
BlobContainerClient containerClient = new BlobContainerClientBuilder()
.connectionString(connectionString)
.containerName(containerName)
.buildClient();
BlobClient client = containerClient.getBlobClient(fileName);
String base64Data = imageBase64Encoded.split(",")[1];
byte[] base64DataBytes = Base64.getDecoder().decode(base64Data);
ByteArrayInputStream dataStream = new ByteArrayInputStream(base64DataBytes);
client.upload(dataStream, base64DataBytes.length);
HttpResponseMessage returning File from webApi with gibberish characters.
I tried setting encoding on header but not helping.
var dataBytes = File.ReadAllBytes(path);
string fileName = Path.GetFileName(path);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
//httpResponseMessage.Content.Headers.Add("Content-Transfer-Encoding", "utf-8");
//httpResponseMessage.Content.Headers.Add("charset", Encoding.ASCII.ToString());
//httpResponseMessage.Content.Headers.Add("charset", "utf-8");
//httpResponseMessage.Content.Headers.ContentEncoding.Add("gzip");
httpResponseMessage.Content.Headers.ContentEncoding.Add("utf-8");
return httpResponseMessage;
All the lines that are commented out were tried and didn't solve the issue.
Thanks.
I need to create a WebAPI method which downloads a file. The file is being correctly downloaded, however the download seems to remain stuck at almost 100% percent in the client browser (ie it doesn't terminate although the file would have downloaded and can be opened). It remains like that for a couple of minutes before terminating. What could the problem be? The following is some test code which replicates my issue
[HttpGet]
public HttpResponseMessage GetFile()
{
string fileName = #"c:\temp\test.zip";
MemoryStream responseStream = new MemoryStream();
using (FileStream source = File.Open(fileName, FileMode.Open))
source.CopyTo(responseStream);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(responseStream);
response.StatusCode = HttpStatusCode.OK;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentTypeHelper.Instance.GetFileContentType(fileName));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentLength = responseStream.Length;
return response;
}
Looks like you need to rewind the MemoryStream after copying:
MemoryStream responseStream = new MemoryStream();
using (FileStream source = File.Open(fileName, FileMode.Open))
source.CopyTo(responseStream);
responseStream.Seek(0, SeekOrigin.Begin);
I have this code to upload a rar file to server and this works. But when i download the file from server, contents of file are spoiled. Please tell me how can I fix that. Thanks.
public ActionResult UpFile(HttpPostedFileBase upFile)
{
string fileName = System.IO.Path.GetFileName(upFile.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myhostaddress.com/" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("myUserName", "MyPassword");
StreamReader streamReader = new StreamReader(upFile.InputStream);
byte[] fileContents = Encoding.Default.GetBytes(streamReader.ReadToEnd());
streamReader.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return RedirectToAction("/");
}
This code is working for me, try it:
var request = (FtpWebRequest)WebRequest.Create(ftp + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, pass);
using (var input = File.OpenRead(filePth))
{
using (var output = request.GetRequestStream())
{
input.CopyTo(output);
}
}
var response = (FtpWebResponse)request.GetResponse();
response.Close();
I'm using GSON for a project. In particular I use this code to generate JSON strings:
Gson gs = new Gson();
JsonObject cmdobj = new JsonObject();
cmdobj.addProperty("cmd", cmd);
cmdobj.add("arg", args);
String cmdstr = cmdobj.toString();
which produces something like:
{"cmd":"HANDSHAKE","arg":{"protocol":"syncmanager","serverName":"12345678910"}}
then on a client machine this reads the json data:
String cmdstr = readCommand(this.is);
Gson gs = new Gson();
JsonObject jsobj = gs.fromJson(cmdstr, JsonObject.class);
JsonElement cmd = jsobj.get("cmd");
JsonObject args = jsobj.get("arg").getAsJsonObject();
the problem is that jsobj that should contain the parsed object doesn't contain anything ( if I do toString() prints {} ). Why this? I just want the JSonObject tree that I had on the other side, not an object serialization. Any clues?
JsonObject jsobj = new Gson().fromJson(cmdstr, JsonObject.class)
will try and build a type of JsonObject from the string - which your string clearly isn't.
I think what you want to do is get the raw parse tree - which you can do like this:
JsonObject jsobj = new JsonParser().parseString(cmdstr);
See this for more details.