I have Spring Boot code with image upload as follows. Can anyone tell me how to not save the book when I don't upload pictures when I press save?
Here is code in controller
#PostMapping("/books")
public String saveBook(#ModelAttribute("book") Book book, Model model, BindingResult bindingResult, #RequestParam(value = "image") MultipartFile image) throws IOException { bookValidator.validate(book, bindingResult);
model.addAttribute("categories", bookCategoryService.findAll());
model.addAttribute("mode", "create");
if (bindingResult.hasErrors()) {
return "create_book";
}
String fileName = null;
if(image.getOriginalFilename() != null) {
fileName = StringUtils.cleanPath(image.getOriginalFilename());
book.setPhotos(fileName);
}
Book savedBook = bookService.saveBook(book);
String uploadDir = "book-photos/" + savedBook.getId();
if(fileName != null) {
FileUploadUtil.saveFile(uploadDir, fileName, image);
}
return "redirect:/";
}
This is code in FileUploadUtil
package com.example.bookmanagement.util;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadUtil {
public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
}
}
You can add validation while you are saving image details in saveBook business method ::
String fileName = null;
if (image != null && image.getOriginalFileName() != null) {
fileName = StringUtils.cleanPath(image.getOriginalFilename());
book.setPhotos(fileName);
Book savedBook = bookService.saveBook(book);
String uploadDir = "book-photos/" + savedBook.getId();
FileUploadUtil.saveFile(uploadDir, fileName, image);
}
Just ignore the save snippet when you are not uploading pictures.
Related
In this service class where can i write the file compression code and am saving the file as "Base64" format in database. The single file is uploaded in s3 bucket but when i upload the MultipartFile[] using postman in aws s3 bucket am getting the "413 Request Entity Too Large" error.How can i solve this error.
This is my service class
#Component
public class TeacherGalleryService {
#Autowired
TeacherGalleryRepository galleryRepo;
private AmazonS3 amazonS3;
#Value("${aws.access.key.id}")
private String accessKey;
#Value("${aws.access.key.secret}")
private String secretKey;
#Value("${aws.region}")
private String region;
#Value("${aws.s3.audio.bucket}")
private String s3Bucket;
#Value("${aws.endpointUrl}")
private String endpointUrl;
#SuppressWarnings("deprecation")
#PostConstruct
private void initializeAmazon() {
System.out.println(accessKey);
AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
this.amazonS3 = new AmazonS3Client(credentials);
}
public String uploadFile(MultipartFile file) {
String fileUrl = "";
try {
File myFile = convertMultiPartToFile(file);
String fileName = generateFileName(file);
fileUrl = endpointUrl + "/" + s3Bucket + "/" + fileName;
uploadFileTos3bucket(fileName, myFile);
myFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
return fileUrl;
}
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;
}
private String generateFileName(MultipartFile multiPart) {
return multiPart.getOriginalFilename().replace(" ", "_");
}
private void uploadFileTos3bucket(String fileName, File file) {
amazonS3.putObject(new PutObjectRequest(s3Bucket, fileName, file)
.withCannedAcl(CannedAccessControlList.PublicRead));
}
public TeacherGallery storeFile(TeacherGallery teacherGallery, MultipartFile file) {
String fileNames = StringUtils.cleanPath(file.getOriginalFilename());
String fileUrls = endpointUrl + "/" + s3Bucket + "/" + fileNames;
byte[] images = null;
try {
images = Base64.encodeBase64(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
teacherGallery = new TeacherGallery(images, fileNames, fileUrls, teacherGallery.getTitle());
return galleryRepo.save(teacherGallery)
}
}
This does seem to be low size configured in Spring's servlet container. Take a look at Web properties for your Spring Boot:
You want to look into these properties
spring.servlet.multipart.max-file-size (default 1MB)
spring.servlet.multipart.max-request-size (default 10 MB)
I am trying to store a file from user, using Java Spring boot and make a preview immediately after image upload. But now I get a 404 error on the console and when I refresh the page, the image shows up!
I tried to solve the problem by adding sleep or delay in the thread. Did not work. Here is some part of controller and service file:
public Resource getIllustrationAsResource(long id) throws MalformedURLException {
return new FileUrlResource(uploadLocation + id + ILLUSTRATION_FILE_ENDING);
}
public PostResult addIllustration(MultipartFile file) throws IOException {
Illustration illustration = getIllustrationMetadata(file);
long id = repo.insertIllustration(illustration);
storeFile(file, id);
return new PostResult(id);
}
private void storeFile(MultipartFile file, long id) throws IOException {
Path path = Paths.get(uploadLocation + id + ILLUSTRATION_FILE_ENDING);
System.out.println("storeFile path: " + path);
File uploadFile = new File(uploadLocation);
uploadFile.getParentFile().mkdirs();
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, path);
}
}
Controller:
#GetMapping("/illustrations/{id}/image")
public ResponseEntity < Resource > getImageContent(#PathVariable("id") long id)
throws MalformedURLException {
Illustration illustrationInfo = service.getOneIllustration(id);
Resource body = service.getIllustrationAsResource(id);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(illustrationInfo.getMime()));
return new ResponseEntity < > (body, headers, HttpStatus.OK);
}
#PostMapping("/illustrations")
public PostResult postOneIllustration(#RequestParam("file") MultipartFile image)
throws IOException {
ProjectId project = projectService.getCurrentProject();
if (project == null) {
throw new EntityMissingException();
}
if (!authorizationService.loggedInUserCanCreateObjectsInProject(project)) {
throw new EntityMissingException();
}
return service.addIllustration(image);
}
Frontend:
postFile: async function(data) {
//console.log("here")
try {
let fetchPromise = catchReject(
fetch(`${window.contextPath}/illustrations`, {
method: 'POST',
body: data
})
)
const response = await fetchPromise
validateHttpOkStatus(response)
return response.json()
} catch (e) {
console.log('in postFile')
console.log(e)
// store.dispatch(addGlobalError(e))
throw e
}
},
I am working on an application which will download 3rd party dependencies to a particular folder and then execute dependency check on it. The files downloaded can be of any type, they can be zip, jar or may b a folder. I am trying to find a code example but nothing seems to work for me. I tried NIO in java but that seems to work only for writing to a particular file not folder. Below is code where I used NIO
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
}
if(rbcObj != null) {
rbcObj.close();
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}```
public Class CopyAndWrite {
public static final String SOURCES = "C:\\Users\\Administrator\\Desktop\\resources";
public static final String TARGET = "C:\\Users\\Administrator\\Desktop\\111";
public static void main (String[]args) throws IOException {
Path startingDir = Paths.get(SOURCES);
Files.walkFileTree(startingDir, new FindJavaVisitor());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!StringUtils.equals(dir.toString(), SOURCES)) {
Path targetPath = Paths.get(TARGET + dir.toString().substring(SOURCES.length()));
if (!Files.exists(targetPath)) {
Files.createDirectory(targetPath);
}
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path targetPath = Paths.get(TARGET + file.toString().substring(SOURCES.length()));
copyFile(targetPath, Files.readAllBytes(file));
return FileVisitResult.CONTINUE;
}
}
private static void copyFile (Path path,byte[] bytes){
// write file
try {
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using OKHttpClient to download the file and place in a folder.
Request request = new Request.Builder().url(downloadUrl).build();
Response response;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
fileName = abc.zip
Path targetPath = new File(inDir + File.separator + fileName).toPath();
try (FileOutputStream fos = new FileOutputStream(targetPath)) {
fos.write(response.body().bytes());
}
return 0;
}
} catch (IOException e) {
logger.error(e.getMessage());
}```
So I'm using Spring to generate random stories and I am getting a NullPointerException on line 73 of the controller which is where I call the ApplicationContext to make a BeanFactory in the function that gets the beans (MadLib and PartOfSpeech classes) from text files. The context was working just fine before I added that function. What's wrong?
Edit: I do know what a NullPointerException is. I don't know why it's happening here. Also, it works when I comment out the constructor. I think the problem might be that I'm trying to call the context before it exists?
Edit 2: I tried moving the call to getBeansFromFiles() to the first GetMapping(links). This took away the NullPointerException, probably because the Controller bean had already been initialized, so the context existed. But while the MadLibs got added to the list, the beans were not created or at least not autowired. Is there a place I can put this call where both will work? Do I need to implement an interface that will make this call at the right time?
package controllers;
import...
#Controller
#RequestMapping(value = "/madLib")
public class MadLibController {
#Autowired
ApplicationContext context;
public MadLibController(){
getBeansFromFiles();
}
public PartOfSpeech pos(String path){
String input;
try {
input = utility.Util.readFile(path);
} catch (IOException e) {
e.printStackTrace();
input = "v";
}
return new PartOfSpeech(input);
}
public MadLib ml(String path){
String input;
System.out.println(new File("").getAbsolutePath());
try {
input = utility.Util.readFile(path);
} catch (IOException e) {
e.printStackTrace();
input = "v#V#v";
}
return new MadLib(input);
}
public void getBeansFromFiles() {
AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
File folder = new File("../../txt/ml");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles){
System.out.println("File path: " + file.getPath());
MadLib ml = ml(file.getPath());
String beanName = ml.getId();
beanFactory.autowireBean(ml);
beanFactory.initializeBean(ml, beanName);
((MadLibList)context.getBean("madLibList")).getList().add(ml);
}
folder = new File("../../txt/pos");
listOfFiles = folder.listFiles();
for (File file : listOfFiles){
System.out.println("File path: " + file.getPath());
PartOfSpeech pos = pos(file.getPath());
String beanName = pos.getId();
beanFactory.autowireBean(pos);
beanFactory.initializeBean(pos, beanName);
}
}
/*#Bean("verb")
public PartOfSpeech verb(){
return pos("verb");
}
#Bean("hansel2")
public MadLib hansel2(){
return ml("hansel");
}
#Bean("lunch")
public MadLib lunch(){
return ml("lunch");
}*/
#GetMapping
public String links(Model model){
MadLibList list = (MadLibList)context.getBean("madLibList");
//list.getList().add(hansel2());
//list.getList().add(lunch());
model.addAttribute("madLibList", list);
return "madLibLinks";
}
#GetMapping("/{name}")
public String prompts(HttpServletRequest req, HttpServletResponse res,
Model model, #PathVariable("name") String name,
#RequestParam(value = "random", defaultValue = "false") String random){
MadLib madLib = (MadLib)context.getBean(name);
madLib.setAnswers(new ArrayList<String>(madLib.getPrompts().size()));
System.out.println("Answers: " + madLib.getAnswers());
if (random.equals("true")){
System.out.println("Prompts: " + madLib.getPrompts());
for (int i=0; i<madLib.getPrompts().size(); i++){
try {
String posBean = utility.Util.camelCase(madLib.getPrompts().get(i));
PartOfSpeech pos = (PartOfSpeech)context.getBean(posBean);
String word = pos.getWord();
System.out.println(word);
madLib.getAnswers().add(word);
} catch (Exception e) {
System.out.println("exception in randomizing answers for " + madLib.getPrompts().get(i));
System.out.println(e);
madLib.getAnswers().add("");
}
}
}
model.addAttribute("default", "");
model.addAttribute("madLib", madLib);
return "madLibPrompts";
}
#PostMapping(value = "/result")
public String result(Model model, #ModelAttribute("madLib") MadLib madLib, BindingResult result){
System.out.println(madLib.getAnswers().get(0));
//model.addAttribute(madLib);
return "madLibResult";
}
}
Implement BeanDefinitionRegistryPostProcessor and use beanFactory instead of context
package controllers;
import...
#Controller
#RequestMapping(value = "/madLib")
public class MadLibController implements BeanDefinitionRegistryPostProcessor {
#Autowired
ApplicationContext context;
ConfigurableListableBeanFactory beanFactory;
private BeanDefinitionRegistry registry;
public PartOfSpeech pos(String path){
String input;
try {
input = utility.Util.readFile(path);
} catch (IOException e) {
e.printStackTrace();
input = "v";
}
return new PartOfSpeech(input);
}
public MadLib ml(String path){
String input;
System.out.println(new File("").getAbsolutePath());
try {
input = utility.Util.readFile(path);
} catch (IOException e) {
e.printStackTrace();
input = "v#V#v";
}
return new MadLib(input);
}
public void getBeansFromFiles() {
File folder = new File("../../txt/ml");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles){
System.out.println("File path: " + file.getPath());
MadLib ml = ml(file.getPath());
String beanName = ml.getId();
beanFactory.registerSingleton(beanName, ml);
((MadLib)beanFactory.getBean(beanName)).setId(ml.getId());
((MadLib)beanFactory.getBean(beanName)).setTitle(ml.getTitle());
((MadLib)beanFactory.getBean(beanName)).setAnswers(ml.getAnswers());
((MadLib)beanFactory.getBean(beanName)).setPrompts(ml.getPrompts());
((MadLib)beanFactory.getBean(beanName)).setStrings(ml.getStrings());
((MadLibList)beanFactory.getBean("madLibList")).getList().add(ml);
}
folder = new File("../../txt/pos");
listOfFiles = folder.listFiles();
for (File file : listOfFiles){
System.out.println("File path: " + file.getPath());
PartOfSpeech pos = pos(file.getPath());
String beanName = pos.getId();
beanFactory.registerSingleton(beanName, pos);
((PartOfSpeech)beanFactory.getBean(beanName)).setName(pos.getName());
((PartOfSpeech)beanFactory.getBean(beanName)).setWords(pos.getWords());
}
}
#GetMapping
public String links(Model model){
MadLibList list = (MadLibList)beanFactory.getBean("madLibList");
model.addAttribute("madLibList", list);
return "madLibLinks";
}
#GetMapping("/{name}")
public String prompts(HttpServletRequest req, HttpServletResponse res,
Model model, #PathVariable("name") String name,
#RequestParam(value = "random", defaultValue = "false") String random){
MadLib madLib = (MadLib)beanFactory.getBean(name);
//System.out.println(madLib);
madLib.setAnswers(new ArrayList<String>(madLib.getPrompts().size()));
System.out.println("Answers: " + madLib.getAnswers());
if (random.equals("true")){
System.out.println("Prompts: " + madLib.getPrompts());
for (int i=0; i<madLib.getPrompts().size(); i++){
try {
String posBean = utility.Util.camelCase(madLib.getPrompts().get(i));
PartOfSpeech pos = (PartOfSpeech)beanFactory.getBean(posBean);
String word = pos.getWord();
System.out.println(word);
madLib.getAnswers().add(word);
} catch (Exception e) {
System.out.println("exception in randomizing answers for " + madLib.getPrompts().get(i));
System.out.println(e);
e.printStackTrace();
madLib.getAnswers().add("");
}
}
}
model.addAttribute("default", "");
model.addAttribute("madLib", madLib);
return "madLibPrompts";
}
#PostMapping(value = "/result")
public String result(Model model, #ModelAttribute("madLib") MadLib madLib, BindingResult result){
System.out.println(madLib.getAnswers().get(0));
//model.addAttribute(madLib);
return "madLibResult";
}
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
this.beanFactory = arg0;
getBeansFromFiles();
}
#Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0) throws BeansException {
this.registry = arg0;
}
}
I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}