I uploaded a batch file from the html frontend.
In my controller, i am trying to process it
public #ResponseBody void customerBatchUpload(#RequestParam("batchFile") MultipartFile[] batchFile) throws Exception {
File fileToImport = new File(batchFile[0].getOriginalFilename());
String pathToFile = fileToImport.getAbsolutePath();
FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
reader.setResource(new FileSystemResource(pathToFile));
reader.open(new ExecutionContext());
}
In the above code the line reader.open(new ExecutionContext()); throws a error of
java.lang.IllegalStateException: Input resource must exist (reader is in 'strict' mode): file [C:\Users\user\Desktop\criticialTest5.csv]
at org.springframework.batch.item.file.FlatFileItemReader.doOpen(FlatFileItemReader.java:251)
I tried I tried String pathToFile = "file://"+ fileToImport.getAbsolutePath(); and
String pathToFile = "file:\\"+ fileToImport.getAbsolutePath();
both failed and gave same above error.
Javadoc of String getOriginalFilename():
Return the original filename in the client's filesystem.
Your server cannot access the client filesystem. How could it?
You need to call either byte[] getBytes(), InputStream getInputStream(), or transferTo(File dest), to get access to the uploaded file content.
In your case, perhaps using InputStreamResource is the best option:
try (InputStream in = batchFile[0].getInputStream()) {
FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
reader.setResource(new InputStreamResource(in));
reader.open(new ExecutionContext());
// more code here
}
If that doesn't work, and uploaded file size is limited, you can use getBytes() and a ByteArrayResource.
If memory is at a premium, or you need to handle huge files, write the uploaded content to a temporary file using transferTo(file) and a FileSystemResource. Remember to delete the temporary file when done.
Related
I am trying to grab a file (in this case an image) from the file system and display it. I can do it from a resources subdirectory just fine, but when I try to go to the file system it is giving me a FileNotFound exception.
java.io.FileNotFoundException: file:\Y:\Kevin\downloads\pic_mountain.jpg (The filename, directory name, or volume label syntax is incorrect)
All the rest of my code is vanilla spring boot that was generated from the Initialize. Thanks.
#RestController
public class ImageProducerController {
#GetMapping("/get-text")
public #ResponseBody String getText() {
return "Hello World";
}
#GetMapping(value = "/get-jpg", produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage(HttpServletResponse response) throws IOException {
FileSystemResource imgFile = new FileSystemResource("file:///Y:/Kevin/downloads/pic_mountain.jpg");
// ClassPathResource imgFile = new ClassPathResource("images/pic_mountain.jpg");
System.out.println(imgFile.getURL());
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
}
}
from the docs:
public FileSystemResource(String path)
Create a new FileSystemResource from a file path
the constructor expects a path-part of the url, so in your case only Y:/Kevin/downloads/pic_mountain.jpg
so you should try to use it this way:
FileSystemResource imgFile = new FileSystemResource("Y:/Kevin/downloads/pic_mountain.jpg");
Btw. could it be, that you miss "Users" in your path? -> Y:/Users/Kevin/downloads/pic_mountain.jpg
I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.
In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.
DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
#Override
public InputStream onCompleted(Response resp) {
try {
String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
String[] columnNames = {"City"};
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
Map<String,Object> params = new HashMap<>();
JasperPrint jPrint = JasperFillManager.fillReport(
resp.getResponseBodyAsStream(),
params,
new JRTableModelDataSource(dtm)
);
JasperViewer jpView = new JasperViewer(jPrint,false);
jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jpView.setSize(800, 600);
jpView.setLocationRelativeTo(null);
jpView.setVisible(true);
} catch (JRException ex) {
System.out.println(ex.getMessage());
}
return resp.getResponseBodyAsStream();
}
});
From my code above, i got an error Error loading object from InputStream
normally i can use
InputStream input = MainContext.class.getResourceAsStream(filename);
But i want to replace file input stream with http request (stream too).
How exactly i can serve .jasper file with http server...?
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).
My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.
finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));
String sFile = new String(bFile);
inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.
byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);
I need to access a file inside the currently executed .jar using a URL.
URL url = BlockConverter.class.getResource("/test.txt");
System.out.println(url.toString());
InputStream is = url.openStream();
This is what I did.
The output is:
jar:file:/C:/Users/User/Desktop/SERVER/plugins/MyJar.jar!/test.txt
My InputStream always ends up throwing an IOException when being initialized, even though the URL is being output correctly.
So how is that possible?
Why can't I open the stream?
EDIT:
Also, please don't answer with "use getResourceAsStream", since it uses the same kind of code:
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
I would open it as a stream directly e.g.
InputStream is = BlockConverter.class.getResourceAsStream("/test.txt");
The above method is the way I normally access resources within a jar (it will open the resource regardless of it being packaged within a jar, or simply as an unpackaged deployment, note)
I'm using primefaces upload file component everything works fine :
my problem that I need to retrieve the uploaded file :
public void handleFileUpload(FileUploadEvent event) {
selectedFile=(File) event.getFile();
}
the uploaded file has DefaultUploadedFile type class but I need File class type . I try to cast it but I get cast error so i found another solution it's creating the file using the DefaultUploadedFile URI
selectedFile=new File(Uri)
but I couldn't find a way to retrieve it from event.getFile()
Any idea will be appreciated
I don't think that you can cast ist to java.io.File. The instance returned by the getFile() method is of type UploadedFile (which is completely unrelated to java.io.File). You could however use the getInputStream() method in order to retrieve an InputStream and read the file like so:
UploadedFile file = event.getFile();
InputStream in = file.getInputStream();
// do something useful with the input stream...
The UploadedFile interface provides other useful methods to inspect the uploaded file. For more information see: http://www.dzeek.net/javadoc/primefacesdocs/org/primefaces/model/UploadedFile.html
In your method get InputStream from UploadedFile. And from InputStream it is easy way to have File. Example (How to convert InputStream to File in Java)
public void handleFileUpload(FileUploadEvent event) {
UploadedFile selectedFile = event.getFile();
InputStream inputStream = selectedFile.getInputstream();
...
}
I am uploading file using spring MVC and jquery. Inside my class method I have written
#RequestMapping(value="attachFile", method=RequestMethod.POST)
public #ResponseBody List<FileAttachment> upload(
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpSession session) {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
//Save the file to a temporary location
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
fileName = realContextPath +"/images/"+file.getOriginalFilename();
//File dest = new File(fileName);
try {
//file.transferTo(dest);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fileName);
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its uploading the file correctly I am using
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
to get the path. My first question is , Is this the correct way to get the path and it stores the file somewhere at
workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images
and when I am trying to display this image on my jsp page using the following code
<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />
It does not display the image, Its generating the following html
<img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">
Am I doing the things right? In my project I have to upload large number of files everyday.
Please let me know if you need anything else to understand my question
It will be better if you upload your files in some directory by absolute path(e.g. C:\images\) instead of relative (your approach). Usually, web apps runs on linux mathines on production and it is good practice to make save path configurable.
Create some application property which will holds save path for files(in xml or property file).