png file Uploading Restful Web Service java - java

I try to write an image file uploading post method for my web service. Here is my post method. The image file can be uploaded into post method but can not converted into Image type.
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/html")
public Response uploadFile(#FormDataParam("file") File file2) throws IOException {
InputStream IS = null;
String output = "";
try {
IS = new FileInputStream(file2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
try {
if (file2 != null && IS != null) {
Image img = ImageIO.read(IS);
if (img != null) {
output = "image file transmission sucessed";
} else {
String out = convertStreamToString(IS);
output = "file uploaded into post method, however can not transfer it into image type "+
"\n"+ out;
}
} else if (file2 == null) {
output = "the file uploaded into post method is null";
}
} catch (IOException e) {
e.printStackTrace();
}
return Response.status(200).entity(output).build();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
The "file uploaded into post method, however can not transfer it into image type "+"\n"+ out; message is shown. The reason I believe is the inputStream contants extral file information + the content of the image. When I try to convert the inputStream back to Image, I need to find a way to get rid of the extra info passed.
here is my new reversion:
#POST
#Path("/images")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response imageUpload(
#FormDataParam("image") InputStream hereIsImage,
#FormDataParam("image") FormDataContentDisposition hereIsName) {
String path = "f://";
if (hereIsName.getSize() == 0) {
return Response.status(500).entity("image parameter is missing")
.build();
}
String name = hereIsName.getFileName();
path += name;
try {
OutputStream out = new FileOutputStream(new File(path));
int read;
byte[] bytes = new byte[1024];
while ((read = hereIsImage.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
return Response.status(500)
.entity(name + " was not uploaded\n" + e.getMessage())
.build();
}
return Response.status(200).entity(name + " was uploaded").build();
}
However, when I upload the image, an error pops up:
[ERROR] An exception occurred during processing of the au.edu.rmit.srtwebservice.util.rest.testWS class. This class is ignored.
com/sun/jersey/core/header/FormDataContentDisposition
the testWS.calss is where my method is.

public Response uploadFile(#FormDataParam("file") File file2)
File input may not work because you most likely be sending an octet stream from your client. So try using InputStream as the input type and hopefully it should work.
public Response uploadFile(#FormDataParam("file") InputStream file2)

Related

Not able to read InputStream data in rest api

I am passing file/img(form data) from my angular app to my rest api as a post method body.
But i am not able to read inputStream content.
My Rest api method:-
#RequestMapping(path = "/upload", method = RequestMethod.POST)
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void process(#FormDataParam("file") InputStream dataStream) throws IOException {
this.writeToFile(dataStream, "src/main/resources/targetFile.jpg");
}
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
byte[] image = IOUtils.toByteArray(uploadedInputStream);
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
IOUtils.write(image, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
image array is always empty and hence empty file gets created in destination dir.
Anything wrong with the implementation?
You can code rest service like this.
Controller method
#RequestMapping(value="/upload", method=RequestMethod.POST)
public void handleFileUpload(#RequestParam("file") MultipartFile file){
writeToFile(file, "src/main/resources/targetFile.jpg");
}
writeToFile method
private void writeToFile(MultipartFile file, String uploadedFileLocation) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(uploadedFileLocation)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("Empty file");
}
}

Download images with Retrofit return empty file

I followed the instruction on the Retrofit page to download an image, however, without the #Streaming tag, the inputstream.read(buffer) would be equal -1 immediately, rendering the file empty. (the image is quite small, only a few hundred kb)
Even when I use the #Streaming tag, the app would keep crashing when I use the inputstream due to IllegalStateException
I tried HttpConnection and I could download the image just fine. However, I really want to make it work with Retrofit
public static String downloadImage(String bearer, long pictureId,Context context){
String path = "";
NetworkAPI apiService = NetworkClient.getClient().create(NetworkAPI.class);
//Call<ResponseBody> downloadCall = apiService.downloadImage(bearer,pictureId);
Call<ResponseBody> downloadCall = apiService.downloadFileWithDynamicUrlSync("https://androidtutorialpoint.com/api/RetrofitAndroidImageResponse");
try {
Response<ResponseBody> response = downloadCall.execute();
if(response.isSuccessful()) {
Log.d(TAG, "success download" + response.body().string());
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
OutputStream out = null;
try {
in = response.body().byteStream();
File file = PictureUtil.createImageFile(context);
Uri photoURI = FileProvider.getUriForFile(context,
"vn.com.wk.bradleyaudit.fileprovider",
file);
out = new FileOutputStream(file);
long fileSize = response.body().contentLength();
long downloadedSize = 0;
Log.d("DownloadImage", "size"+fileSize);
byte[] buffer = new byte[4096];
while (true) {
int bufferLength = in.read(buffer);
Log.d("DownloadImage", "buffer Length"+bufferLength);
if (bufferLength == -1) {
break;
}
out.write(bufferLength);
out.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
out.flush();
path = photoURI.toString();
Log.d("DownloadImage", "path"+path);
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
Try this,
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
also add the dependancy;
compile 'com.squareup.picasso:picasso:2.5.2'

Nullpointer exception soapui file upload call

I have to upload a file using soap ui.Below is my service code.It executes fine if call using jersey.But when i try to call using soapui null pointer exception occurs.
I call the fileupload service in soap ui like below
Create Rest Project:
Add the Url:
http://localhost:8080/FileService/Services/HomeService/testupload
file file:c:\\1.wav
#POST
#Path("testupload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public String uploadFile(#FormDataParam("file") InputStream fis,
#FormDataParam("file") FormDataContentDisposition fdcd) {
OutputStream outpuStream = null;
String fileName = fdcd.getFileName();
String filePath = FOLDER_PATH + fileName;
try {
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(filePath));
while ((read = fis.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch(IOException iox){
iox.printStackTrace();
} finally {
if(outpuStream != null){
try{outpuStream.close();} catch(Exception ex){}
}
}
return "File Upload Successfully !!";
}
How to fix this issue? Any help will be greatly appreciated!!!

Missing bytes when calling HttpServletRequest.getInputSteam() method

I am creating Restful web service that accepts any file and saves it into filesystem. I am using Dropwizard to implement the service and Postman/RestClient to hit the request with data. I am not creating multipart (form-data) request.
Every thing is working fine except the file saved has first character missing. Here is my code for calling the service method and saving it into file system:
Input Request:
http://localhost:8080/test/request/Sample.txt
Sample.txt
Test Content
Rest Controller
#PUT
#Consumes(value = MediaType.WILDCARD)
#Path("/test/request/{fileName}")
public Response authenticateDevice(#PathParam("fileName") String fileName, #Context HttpServletRequest request) throws IOException {
.......
InputStream inputStream = request.getInputStream();
writeFile(inputStream, fileName);
......
}
private void writeFile(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
File file = new File(this.directory);
file.mkdirs();
if (file.exists()) {
os = new FileOutputStream(this.directory + fileName);
logger.info("File Written Successfully.");
} else {
logger.info("Problem Creating directory. File can not be saved!");
}
byte[] buffer = new byte[inputStream.available()];
int n;
while ((n = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, n);
}
} catch (Exception e) {
logger.error("Error in writing to File::" + e);
} finally {
try {
os.close();
inputStream.close();
} catch (IOException e) {
logger.error("Error in closing input/output stream::" + e);
}
}
}
In output, file is saved but first character from the content is missing.
Output:
Sample.txt:
est Content
In above output file, character T is missing and this happens for all the file formats.
I don't know what point I am missing here.
Please help me out on this.
Thank You.

call back in spring file upload

i have followed this to upload file to server. the file is getting uploaded but after uploading the file it gives the page name as the filename.extension.jsp and gives HTTP Status 404 here is the screen shot :
But i want to show the user only the status message saying File is uploaded. how to do this?
Here is my spring controller method:
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName = "";
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
fileName = request.getRealPath("") + "/resources/Attachment/"+uploadItem.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName = uploadItem.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
Please help me to find,
Best Regards
Hi #Anto you can do it somethig like this,
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request, ModelMap map) {
String uploadedFileName = "";
...
uploadedFileName = uploadItem.getOriginalFilename();
// ---------------------------------------------------------------------------
if("" != uploadedFileName || null != uploadedFileName) {
map.put("message", new String("File is uploaded."));
} else {
map.put("message", new String("File is not uploaded."));
}
// ---------------------------------------------------------------------------
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
And JSP you put
<c:out value="${message}"></c:out>
I hope help you :)

Categories

Resources