Spring - java.nio.file.FileSystemException: ./folder/file.png: Read-only file system - java

I am trying to upload files using the form:
<form th:action="#{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="files">
<input type="submit" value="Upload Files" accept="image/png, image/jpeg"></input>
</form>
and this is my controller:
private final String UPLOAD_DIR = "./uploads/";
#PostMapping("/upload")
public String upload(#RequestParam("files") MultipartFile file, RedirectAttributes attributes) {
if(file.isEmpty()) {
attributes.addFlashAttribute("message", "Please select a file to upload.");
return "redirect:/";
}
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
Path path = Paths.get(UPLOAD_DIR, fileName);
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
attributes.addFlashAttribute("message", "You successfully uploaded " + fileName + '!');
return "redirect:/";
}
everything works fine on localhost (windows) but my problem is that it doesn't work on the server (linux) because I get an exception:
"java.nio.file.FileSystemException: ./uploads/file.png: Read-only file system" the "uploads" folder has all permissions, please help, I have no ideas anymore.

Related

Auto Upload functionality in spring boot and Ajax

We have one of the banking project where we have requirement where we have to upload the file at the time of uploading It self (means Autoupload)
How to use Ajax call for auto upload using spring boot,
This is the Spring boot Controller I have -
#Controller
public class UploadController {
//Save the uploaded file to this folder
private static String UPLOADED_FOLDER = "F://temp//";
#GetMapping("/")
public String index() {
return "upload";
}
#PostMapping("/upload") // //new annotation since 4.3
public String singleFileUpload(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
#GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
I have in input file field like this
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
Here is the I find and this resolve the issue of this problem and I find which is very useful for this problem of auto uploading at the time of uplaoding time itself. please check this out
$('#certificate_document_other').on("change",function(){
var objFormData=new FormData();// to capture all form form information inform of object
var objFile= $(this)[0].files[0];
objFormData.append('file',objFile);
$.ajax({
url:"/SomeProjetName/fileUpload",
type: "POST",
enctype:"multipart/form-data",
data:objFormData,
contentType:false,
processType:false,
success: function(data){
alert('upload SuccessFull');
},error:function(xhr,status,errorType){
alert(xhr.status);
alert(xhr.responseText);
}
});
});

Spring MVC :- How do i get the uploaded image to display on jsp page as soon as the user selects the image.I am using Spring Framwework here

I have uploaded the file to server but how do i get the image to display in jsp page...what steps do i need to follow?I guess i will need the path of the server location...but how do i get the path or is there a better way?
Controller.java
#RequestMapping(value="/addWebAchievement",method=RequestMethod.POST)
public ModelAndView addAchievement(#RequestParam("image") MultipartFile image,#RequestParam("title")String title,#RequestParam("note")String note,
Map<String,Object>m,#ModelAttribute("classObject") Clazz c ){
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
CustomUser user=null;
if (principal instanceof CustomUser) {
user = ((CustomUser)principal);
}
String username=user.getUsername();
ModelAndView model = new ModelAndView();
String imageName1=image.getOriginalFilename();
if (!image.isEmpty()) {
try {
byte[] bytes = image.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "imageFiles");
System.out.println(dir);
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + imageName1);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
}catch(Exception e){}
}
addAchievement.jsp
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#userPhoto')
.attr('src', "<c:url value="e.target.result"/>")
.width(435)
.height(219);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<img class="activator" src="<c:url value="/resources/image/user-bg.jpg" />" id="userPhoto" alt="user bg" id="default_image">
to preview image when uploading image you can ahieve it by java script
<img src="images/<%=imageName%>" width="300px" height="150px" name="blogimage" id="imgprvw"/><input type="file" id="exampleInputFile" name="blogimage" onchange="showimagepreview(this)">
java script:
<script type="text/javascript">
function showimagepreview(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#imgprvw').attr('src', e.target.result);
}
filerdr.readAsDataURL(input.files[0]);
}
}
</script>
and to diplay image that is already uploaded no need to pass any server location you can directly use path like
<img src="images/<%=imageName%>" width="300px" height="150px" />
here i am assuming that root folder for is images.you can user folder name

Drag Drop file upload with AngularJS and Spring Rest

I have angularjs And spring rest file upload it work well but i need to change file upload in html file to dropzone.js or any drag drop file upload,I tried dropzone.js library but I couldn't integrate it with angular ,Can any one help me how can i do that?
Angularjs controller
$scope.document = {};
$scope.setTitle = function(fileInput) {
var file=fileInput.value;
var filename = file.replace(/^.*[\\\/]/, '');
var title = filename.substr(0, filename.lastIndexOf('.'));
$("#title").val(title);
$("#title").focus();
$scope.document.title=title;
};
$scope.uploadFile=function(){
var formData=new FormData();
formData.append("file",file.files[0]);
$http.post('/app/newDocument', formData, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: { 'Content-Type': undefined }
}).success(function(data, status) {
console.log("Success ... " + status);
}).error(function(data, status) {
console.log("Error ... " + status);
});
};
});
html form
<form ng-submit="uploadFile()" class="form-horizontal"
enctype="multipart/form-data">
<input type="file" name="file" ng-model="document.fileInput" id="file" />
<input type="text" class="col-sm-4" ng-model="document.title" id="title" />
</form>
Rest Controller
#RequestMapping(value="/newDocument", method = RequestMethod.POST)
public void UploadFile(MultipartHttpServletRequest request,
HttpServletResponse response) throws IOException {
Attachment attachment=new Attachment();
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
attachment.setName(fileName);
File dir = new File("D:\\file");
if (dir.isDirectory())
{
File serverFile = new File(dir,fileName);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(file.getBytes());
stream.close();
}else {
System.out.println("not");
}
}
I would personally use a dedicated directive such as the excellent:
https://github.com/danialfarid/angular-file-upload
https://github.com/flowjs/ng-flow
These take care of the boilerplate code and let you focus on styling and creating an upload service that works in sync with your API.

How to upload a file in play framework?

I am new to play framework 2.0 and wanted to upload a file in my local file system. But I have no idea how to start this.can anyone help me here?
Our Form
#form(action = routes.Application.upload, 'enctype -> "multipart/form-data") {
<input type="file" name="picture">
<p>
<input type="submit">
</p>
}
Our Upload action
#BodyParser.Of(value = BodyParser.Text.class, maxLength = 10 * 1024)
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
return ok("File uploaded");
} else {
flash("error", "Missing file");
return redirect(routes.Application.index());
}
}
Just change the maxLength = 10 * 1024(this is just around 10kb) to your desired length more of this can be found on the documentation
if you are gonna send the files via Ajax. use this
public static Result upload() {
File file = request().body().asRaw().asFile();
return ok("File uploaded");
}
The response from above will be encoded as Mutlipart/form-data but will just contain the plain content files

Image upload with Spring REST

I want to upload image with RestTemplate client and get that POST request with Spring base REST sever and save on server. Can any one please help me to how to do this with my Spring base client and server. Thanks
Some of my Spring REST API base server methods are as below,
#RequestMapping(value="user/upload/{imageFile}", method=RequestMethod.POST)
public #ResponseBody User upload(#RequestBody User user, #PathVariable File imageFile, HttpServletResponse response) {
// TODO - How I get this image and file and save, whether I can POST this image file with User object
}
Some of my remote client's Spring RestTemplate base codes are as below,
User newUser = new User();
Map<String, String> vars = new HashMap<String, String>();
vars.put("imageFile", imageFile);
ResponseEntity<User> REcreateUser = restTemplate.postForEntity(IMC_LAB_SKELETON_URL + "/user/upload/{imageFile}", newUser, User.class, vars);
User createUser = REcreateUser.getBody();
// TODO - How I can POST this image file as a parameter or content of the User object
This is a piece of code I wrote time ago (you could pass the filename as a #PathVariable):
server side:
#RequestMapping(value = "/file", method = RequestMethod.POST)
public String uploadFile(#RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
//add your logics here
//File newFile = new File("blablabla.xxx");
//file.transferTo(newFile);
...
test with rest template:
#Test
public void testFileUpload() {
String url = "http://blablabla.com/file";
Resource resource = new ClassPathResource("images/file.xxx");
MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
mvm.add("file", resource);
ResponseEntity<String> respEnt = rt.postForEntity(url, mvm, String.class);
//logger.info("body: " + respEnt.getBody());
...
this bean is needed (I think it requires some apache commons library but I am not sure and don't remember now)
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="500000"/>
</bean>
Refer below code u can upload multiple files,working fine
<form method="POST" enctype="multipart/form-data"
id="fileUploadForm">
<div class="controls">
<div class="entry input-group col-xs-3">
<input class="btn btn-primary" name="files" type="file">
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</form>
JS
$(document).ready(function() {
$("#btnSubmit").click(function(event) {
// stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
// $("#btnSubmit").prop("disabled", true);
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$.ajax({
method : "POST",
enctype : 'multipart/form-data',
url : "lotConfig/lotImage",
data : data,
// http://api.jquery.com/jQuery.ajax/
// https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
processData : false, // prevent jQuery from automatically
// transforming the data into a query string
contentType : false,
cache : false,
timeout : 600000,
success : function(data) {
jQuery('#lotImageget').html('');
getAllLotiamges();
$('#updateImage').modal('hide');
/*
* $("#result").text(data); console.log("SUCCESS : ", data);
* $("#btnSubmit").prop("disabled", false);
*/
},
error : function(e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
// $("#btnSubmit").prop("disabled", false);
}
});
}
Spring controller
#PostMapping(value = "/lotImage")
public ResponseEntity<String> updateLotImage(
#RequestParam("files") MultipartFile[] files,
RedirectAttributes redirectAttributes, HttpSession session)
throws IOException {
logger.info("--got request to update Lot Image--");
StringJoiner sj = new StringJoiner(" , ");
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue; // next pls
}
try {
byte[] bytes = file.getBytes();
Properties prop = new Properties();
String resourceName = "app.properties";
ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
InputStream resourceStream = loader
.getResourceAsStream(resourceName);
try {
prop.load(resourceStream);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String image_path = prop.getProperty("LOT_DESTINATION_IMG");
Path path = Paths.get(image_path
+ file.getOriginalFilename());
Files.write(path, bytes);
sj.add(file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("--Image updated--");
return new ResponseEntity<String>("Success", HttpStatus.OK);
}

Categories

Resources