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");
}
}
Related
I'm using the following REST method to be called from the UI to download the ZIP archive:
#RequstMapping("/download")
public void downloadFiles(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_OK);
try {
downloadZip(response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("Unable to download file");
}
}
private void downloadZip(OutputStream output) {
try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
byte[] bytes = getBytes();
zos.write(bytes);
zos.closeEntry();
} catch (Exception e) {
throw new RuntimeException("Error on zip creation");
}
}
It's working fine, but I wanted to make the code more Spring oriented, e.g. to return ResponceEntity<Resource> instead of using ServletOutputStream of Servlet API.
The problem is that I couldn't find a way to create Spring resource from the ZipOutputStream.
Here is a way to return bytestream, you can use it to return zip file as well by setting content-type.
#RequestMapping(value = "/download", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Resource> download() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
InputStream is = null; // get your input stream here
Resource resource = new InputStreamResource(is);
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
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)
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!!!
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 :)
My requirement is, I should send a 10MB zip file to the client with a restful service. I found the code in forums that sending a StreamingOutput object is the better way, but how can I create a StreamingOutput object in the following code:
#Path("PDF-file.pdf/")
#GET
#Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException
{
try {
//------
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
}
Its the better way and easy way for file dowload.
private static final String FILE_PATH = "d:\\Test2.zip";
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=newfile.zip");
return response.build();
}
For your code as you asked:
#GET
#Path("/helloWorldZip")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public StreamingOutput helloWorldZip() throws Exception {
return new StreamingOutput(){
#Override
public void write(OutputStream arg0) throws IOException, WebApplicationException {
// TODO Auto-generated method stub
BufferedOutputStream bus = new BufferedOutputStream(arg0);
try {
//ByteArrayInputStream reader = (ByteArrayInputStream) Thread.currentThread().getContextClassLoader().getResourceAsStream();
//byte[] input = new byte[2048];
java.net.URL uri = Thread.currentThread().getContextClassLoader().getResource("");
File file = new File("D:\\Test1.zip");
FileInputStream fizip = new FileInputStream(file);
byte[] buffer2 = IOUtils.toByteArray(fizip);
bus.write(buffer2);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}