I have following controller:
#PostMapping(value = "/load_attachment")
public DeferredResult uploadingPost(#RequestParam("attachment") MultipartFile[] uploadingFiles, #RequestParam("stoneId") String stoneId) throws IOException {
logger.info("Upload {} files for stone: {}", uploadingFiles.length, stoneId);
for (MultipartFile uploadedFile : uploadingFiles) {
File file = new File(uploadedFile.getOriginalFilename());
uploadedFile .transferTo(file);
logger.info("path:{}", file.getAbsolutePath()); // I expect to find files here
}
}
No exceptions happens but I could not find files on file system.
In your case, Application server doesn't application server inside folder path so you should specify it manually!...
for (MultipartFile uploadedFile : uploadingFiles) {
File file = new File("path/to/your/server/application/directory"+uploadedFile.getOriginalFilename());
uploadedFile .transferTo(file);
logger.info("path:{}", file.getAbsolutePath()); // I expect to find files here
}
for further reference https://www.programcreek.com/java-api-examples/index.php?class=org.springframework.web.multipart.MultipartFile&method=transferTo
Related
I'm using a function like this to get the latest file present based on timestamp:
File file = getFile(path);
Where getFile () is like this:
private File getFile (String path) {
File directory = new File(path);
File[] files = directory.listFiles(File::isFile);
long latestVersion = Long.MIN_VALUE;
File latestFile = null;
if (files!= null) {
for (File file : files) {
if (file.lastModified() > latestVersion) {
latestFile = file;
latestVersion = file.lastModified();
}
}
}
return latestFile;
}
On running mvn clean install I get this error:
IllegalStateException: Failed to load Application Context in a totally different test class of the same module.
If I remove the file method, the build runs fine. Definitely something is wrong here in this code then?
Can anyone help here?
Thanks.
I want to convert csv file contains student data to List and insert into database. I have gone through many examples from various sources, none of them provides answer for batch processing csv files uploaded from Web UI using spring batch. All examples process csv files located in resource folder (classpath).
Please help me to process csv files uploaded using Post Method as below.
#PostMapping("/save")
public ResponseEntity saveStudentDetails(#RequestParam("file") MultipartFile studentCSV) {
//code to initate batch processing for studentCSV file
}
Thanks in Advance.
Controller
#RequestMapping(method = RequestMethod.POST, value = "/save")
public ReturnFormat uploadCSV(#RequestParam("files") MultipartFile file )
{
return uploadingService.uploadCSV( file );
}
Service class will be like
public void uploadCSV (MultipartFile multipartFile)
{
ReturnFormat rf = new ReturnFormat();
SuccessErrorList selist = new SuccessErrorList();
try
{
File file = convertMultiPartToFile( multipartFile );
}
private File convertMultiPartToFile( MultipartFile file ) throws IOException
{
File convFile = new File( file.getOriginalFilename() );
FileOutputStream fos = new FileOutputStream( convFile );
fos.write( file.getBytes() );
fos.close();
return convFile;
}
I am testing test in cucumber which i want to upload file from testData to S3 bucket:
String bucket = bucketname+ "/ADL";
String ActualFilesPathForComparison = Environment.getInstance().getValue(DATAINPUTPATH);
temp = ActualFilesPathForComparison+inputPath+ File.separator+ file;
s3.uploadFile(bucket, file, new File (temp));
public void uploadFile(String bucketName, String fileKeyName, File localFilePath) {
try {
this.s3.putObject((new PutObjectRequest(bucketName, fileKeyName, localFilePath)).withCannedAcl(CannedAccessControlList.PublicRead));
} catch (Exception var5) {
throw new RuntimeException("Upload file failed.", var5);
}
}
I have this file:
src\main\resources\testData\testInputsFile\testLZInputUnZippedFiles\Log.csv
when i run the test i am getting from the debug:
localFilePath = testData\testInputsFile\testLZInputUnZippedFiles\Log_WithHeader.csv
And getting excption:
com.amazonaws.SdkClientException: Unable to calculate MD5 hash: testData\testInputsFile\testLZInputUnZippedFiles\Log_WithHeader.csv (The system cannot find the path specified)
what should i fixed? i want to avoid to copy the file outside from the src.
To access a file named "my.properties" which is inside src/main/resources/, you just need to do:
File propertiesFile = new File(this.getClass().getClassLoader().getResource("my.properties").getFile());
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 need to access file system or path a txt file of windows from solaris server. I have a deployment .war into server weblogic solaris, but I don't ability for get out txt file from server to client, in this case windows system or whatever system.
The access to txt files is from,
<input type="file" name="filename" />
I need read the file from client but I'm having FileNotFoundException
PLEASE HELP ME
Your Spring MVC app running on your server does not access the original file on the client's machine (otherwise websites could do bad things to your computer) - the browser sends a copy of the file over the wire to your controller.
Here is a snippet of code I've used to copy the uploaded file to the server's file system:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFile(
HttpServletResponse response,
#RequestParam(value="filename", required=true) MultipartFile multipartFile,
Model model) throws Exception {
if (!multipartFile.isEmpty()) {
String originalName = multipartFile.getOriginalFilename();
final String baseTempPath = System.getProperty("java.io.tmpdir"); // use System temp directory
String filePath = baseTempPath + File.separator + originalName;
File dest = new File(filePath);
try {
multipartFile.transferTo(dest); // save the file
} catch (Exception e) {
logger.error("Error reading upload: " + e.getMessage(), e);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "File uploaded failed: " + originalName);
}
}
}