I have written a spring boot application rest-api to upload file on docker instance inside ec2.
Though I am not getting any errors, the file is not being uploaded to docker container.
#PostMapping(value = "/uploadFile")
public void uploadFile(#RequestPart(name = "file") MultipartFile file)
{
try {
System.out.println("Writing file");
byte[] bytes = file.getBytes();
Path path =Paths.get(uploadPath +file.getOriginalFilename());
System.out.println("Uploaded to :"+uploadPath+file.getOriginalFilename());
Files.write(path, file.getBytes());
}
catch (Exception e) {
System.out.println(e);
}
}
filepath = /home/ubuntu/dockerproject/file-upload/
What I want to achieve is that using the above rest api , the file should get uploaded to file-path location.
I am not able to rectify if the path is wrong or some other issue exists.
Also file-upload has permission 0777.
Related
I have a spring boot rest api which uploads some documents on firestore DB. Problem is when I am running locally it is working absolutely fine without causing any issue. but when I am packaging it as a jar and uploading in AWS beanstalk. That endpoint giving below error response.
{
"timestamp": "2022-11-01T13:53:21.121+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "FirebaseApp with name [DEFAULT] doesn't exist. ",
}
This is how I am reading the firebase service account (file name is serviceaccount.json) file which is located in src/main/resources folder and I have
firebase.credential.resource=serviceaccount.json entry in my application.properties
#Value("${firebase.credential.resource}")
String resourcePath;
#PostConstruct
public void initialize() {
try {
Resource resource = new ClassPathResource(resourcePath);
//FileInputStream serviceAccount = new FileInputStream(resource.getFile());
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(resource.getInputStream()))
.build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I just deployed my first microservice. My microservice is working fine. All routes are working. But the service class inside the microservice is not working properly. The service class is not reading data from the CSV file.
Below is the code I am using to read data from CSV file.
public class ReadCsvUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadCsvUtil.class);
public List<String[]> readData() throws IOException {
String file = ".\\src\\main\\resources\\pensioners.csv";
List<String[]> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
LOGGER.debug(e.getMessage());
}
return content;
}
}
The service class invokes the above function to get details of all the people.
The above code is working fine on my desktop and I am able to get details but code is not working on AWS. Also, I tried to remove the CSV and manually enter the values and it's working in AWS. So I am 99% sure there is some problem in reading the CSV files.
Is there anyway I can fix this?
If the path to the file one directory up, instead of
String file = ".\\src\\main\\resources\\pensioners.csv";
try,
String file = "..\src\main\resources\pensioners.csv";
I presume the AWS sever is ubuntu and your local is windows OS.
I want to make a download functionality which has to download a file from the server using spring boot.
The size limit of the file should be 1gb and I should have an option to download it as a zip file
Hello to download any type of file you can use the following method. You must have configured the path before applying it.
//descargar archivo
#Secured({ "ROLE_ADMIN", "ROLE_USER","ROLE_SADMIN","ROLE_USERGESTSERV"})
#RequestMapping(value="/downloadFile/{filename:.+}")
public void getLogFile(HttpSession session,HttpServletResponse response,#PathVariable String filename) throws Exception {
try {
final Logger log = LoggerFactory.getLogger(getClass());
Path pathFoto = getPath(filename);
log.info("pathFoto: " + pathFoto);
Resource recurso = new UrlResource(pathFoto.toUri());
File fileToDownload = new File(pathFoto.toString());
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;recurso");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception exception){
System.out.println(exception.getMessage());
}
}
Inside my JHipster (version 6.4.1) application in resources I have directory called static, where I put JSON file which is required for one of services. File is called standards.json.
In my service I want to read this file in quite simple way:
try {
ClassPathResource cpr = new ClassPathResource("static/standards.json");
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
String content = new String(bdata, StandardCharsets.UTF_8);
Gson g = new Gson();
data = g.fromJson(content, StandardLevel[].class);
// here I am doing something with data
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
But unfortunately I am getting runtime error:
class path resource [static/standards.json] cannot be opened because it does not exist
It is strange, because when I was doing it in this same way in "clean" Spring Boot application, without JHipster, everything was working correctly.
Any ideas why it is not working here? Or how should I use static JSOn files, which are required for my backend side?
I am facing error MultipartFile error for one day after having upgrade from Spring Boot 1.2.7 to 1.3.1.
What I notice is that the default is now Jetty 9.2 and no more Tomcat 8. Everything was fine until I tried to write an uploaded file using MultipartFile.transferTo(File file) method..
MultipartFile.transferTo() method is calling an implementation of javax.servlet.http.Part Which is implemented this way for tomcat 8
#Override
public void write(String fileName) throws IOException {
File file = new File(fileName);
if (!file.isAbsolute()) {
file = new File(location, fileName);
}
try {
fileItem.write(file);
} catch (Exception e) {
throw new IOException(e);
}
}
and this way for jetty 9.2
public void write(String fileName) throws IOException
{
if (_file == null)
{
_temporary = false;
//part data is only in the ByteArrayOutputStream and never been written to disk
_file = new File (_tmpDir, fileName);
BufferedOutputStream bos = null;
try
{
bos = new BufferedOutputStream(new FileOutputStream(_file));
_bout.writeTo(bos);
bos.flush();
}
finally
{
if (bos != null)
bos.close();
_bout = null;
}
}
else
{
//the part data is already written to a temporary file, just rename it
_temporary = false;
File f = new File(_tmpDir, fileName);
if (_file.renameTo(f))
_file = f;
}
}
What's wrong with the Jetty implementation is that is waiting for file name File.getName() and not the absolute path name File.getPath() which is provided by the call of StandardMultipartHttpServletRequest.transferTo(File file)
#Override
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
}
Is this a bug ? Note that this occurs since I have upgraded from spring boot 1.2.7 to 1.3.1. The default was Tomcat and now it is Jetty...
Per the javadoc for javax.servlet.http.Part.write(String filename) the filename parameter is ...
The file is created relative to the location as specified in the
MultipartConfig
In the code you referenced in Jetty 9.2, namely this ...
jetty-9.2.14.v20151106 - MultiPartInputStreamParser.write(String fileName)
You'll see that there's 2 possible code paths it takes, the first is the "in memory" path, and the second is "file on disk" approach.
In both cases, when you specify a filename to Part.write(String) that name is relative to your MultiPartConfig.location (a configuration of which you haven't detailed in your question).
The implementation of MultiPartInputStreamParser has a _tmpDir which is configured from the webapp's MultiPartConfig.location.
If you want this to behave properly, would highly recommend you define a MultiPartConfig.location that is appropriate for your application, instead of relying on the container to pick one.
The Tomcat approach of allowing absolute filenames in Part.write(String) is actually not allowed in the servlet spec (mainly as its a security issue that can be used to cause havoc on a system)
Ok, at the moment if you want to get rid of this error you can switch back to Tomcat instead of Jetty.
Put tomcat into your dependencies:
compile('org.springframework.boot:spring-boot-starter-tomcat')
And declare tomcat as container:
#Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
return new TomcatEmbeddedServletContainerFactory();
}