call back in spring file upload - java

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 :)

Related

when i write a code for download pdf but only one pdf is download(bcz this pdf is text only) another pdf is not open on spring boot and angular 12

enter image description here
enter image description here
Controller on spring boot--->
#PostMapping(value = "/getpdfs")
public void getSchemeNotes(HttpServletRequest request, #RequestBody String requestBody,HttpServletResponse response) {
MessageLogger.debug(logger, String.format("getSchemeIpoNote(requestBody = %s)", requestBody));
Map<String, String> query = Utility.getQueryParameters(request);
try {
Scheme scheme = (Scheme) DataParsingUtility.convertJsonStringtoObject(requestBody, Scheme.class);
String fileNames= scheme.getSchemeNote();
//String fileNames = "Campus Activewear Limited - IPO Note Apr'2022-compressed.pdf";
String outputPath = ParameterConfiguration.getUploadDirectory() + File.separator + fileNames;
MessageLogger.debug(logger, String.format("fileNames(fileNames = %s)", fileNames));
MessageLogger.debug(logger, String.format("outputPath(outputPath = %s)", outputPath));
InputStream is = null;
try {
is = new FileInputStream(new File(outputPath));
response.setHeader("Content-Disposition", "attachment;filename=\""+fileNames+"\"");
response.setHeader(Constants.FILE_NAME, fileNames);
response.setHeader( "application","blob");
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
finally {
if (is != null) {
is.close();
}
}
} catch (Exception ex) {
MessageLogger.debug(logger, "Error while getting Scheme Note file!", ex);
}
}
angular controller-->
viewNote(obj: any) {
var reqData = {
"schemeNote" : obj
}
this.schemeService.getSchemeNote(null, reqData, (rsp) => {
this.messageLoggerService.debug("request>>>"+JSON.stringify(reqData));
this.messageLoggerService.debug("response>>>>"+rsp);
this.commonService.processDownloadResponse(rsp);
});
}

Spring HttpRequestHandler multifile download

I try to change this one-file download to multi-files download one after one, not in zip. Every time I use this code, it downloads only first file (but the loop continues).
I think it's because of
httpServletResponse.setContentType(mimeType);
I've tried to solve this in some other ways, but nothing has worked.
#Override
public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
List<Example> examples = exampleService.findAll();
for (Example example : examples) {
try {
Blob blob = new SerialBlob(example.getFileContent());
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
String mimeType = example.getContentType();
if (mimeType == null) {
mimeType = "application/octet-stream";
}
httpServletResponse.setContentType(mimeType);
httpServletResponse.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", example.getFileName());
httpServletResponse.setHeader(headerKey, headerValue);
OutputStream outputStream = httpServletResponse.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

png file Uploading Restful Web Service 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)

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!!!

Read pdf files placed at one server from another server

I have two node on production environment. I have placed pdf files at one server and want to read it from both server. when am calling 'file' method directly pdf get displayed in browser but when i call 'pdfFiles' nothing is displayed in browser.
public Resolution file(){
try {
final HttpServletRequest request = getContext().getRequest();
String fileName = (String) request.getParameter("file");
File file = new File("pdf file directory ex /root/pdffiles/" + fileName);
getContext().getResponse().setContentType("application/pdf");
getContext().getResponse().addHeader("Content-Disposition",
"inline; filename=" + fileName);
FileInputStream streamIn = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(streamIn);
int readBytes = 0;
ServletOutputStream stream = getContext().getResponse().getOutputStream();
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (Exception exc) {
LOGGER.logError("reports", exc);
}
return null;
}
public Resolution pdfFile() {
final HttpServletRequest request = getContext().getRequest();
final HttpClient client = new HttpClient();
try {
String fileName = (String) request.getParameter("file");
final String url = "http://" + serverNameNode1 //having pdf files
+ "/test/sm.action?reports&file=" + fileName;
final PostMethod method = new PostMethod(url);
try {
client.executeMethod(method);
} finally {
method.releaseConnection();
}
} catch (final Exception e) {
LOGGER.logError("pdfReports", "error occured2 " + e.getMessage());
}
return null;
}
Included below part of code after 'client.executeMethod(method);' in 'pdfFile()' method and it works for me.
buf = new BufferedInputStream(method.getResponseBodyAsStream());
int readBytes = 0;
stream = getContext().getResponse().getOutputStream();
// write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);

Categories

Resources