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
Related
I am trying to upload files from upload button to a temp folder in server and after upload finished, i would like to see "Successful" message and uploaded filenames List.if user click on delete button from UI, I want to delete the selected file by passing filename in request.Please help me.Below is the code I have written.
#ResponseBody
#JsonIgnore
#RequestMapping(value = "/uploadAttachment", method = RequestMethod.POST, produces = "text/html")
public List<String> uploadAttachment(final MultipartHttpServletRequest request)
{
final List<String> fileNames = new ArrayList<String>();
try
{
final List<MultipartFile> files = request.getFiles("files[]");
final String orderPath = dPUploadOrderAttachmentFacade.createFolderForAttachment();
LOG.info(orderPath);
for (final MultipartFile file : files)
{
if (file.getSize() <=300000) {
dPUploadOrderAttachmentFacade.storeTempFiles(file.getOriginalFilename(), file.getInputStream(), orderPath);
final String fileName = file.getOriginalFilename();
LOG.info(fileName);
fileNames.add(fileName);
}
}
LOG.info(fileNames);
return fileNames;
}
catch (final Exception ex)
{
LOG.error(fileNames+"File Upload Failed due to " );
}
return fileNames;
}
Add the code
request.setAttribute("filenames", fileNames);
JSP
<c:forEach var = "filename" items = ${filenames}>
${filename}
</c:forEach>
Try this
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);
}
});
});
I use Servlet 3.0, PrimeFaces 6.0, WildFly 8.2, Eclipse Neon, Mozilla or Chrome browsers. Despite following these nice links below:
Oracle Tutorial on File Upload
GitHub: getting the original file name example
I am still not able to determine the actual file name of an uploaded file. My problem is that in the below mentioned servlet the method call:
String fileNamer = getFileName(filePart);
gives me back NULL for the file name, i.e. fileNamer is null. What am I doing wrong? Please help:
1.) Here is my controller (servlet):
#WebServlet("/fileUpload")
#MultipartConfig
public class ImageUploadServlet extends HttpServlet {
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
}
}
return null;
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
HttpSession session = request.getSession(false);
Long savedKundeId = (Long) session.getAttribute(NewCustomerBean.SESSION_ATTRIBUTE_CUST_ID);
Part filePart = null;
PrintWriter pw = null;
try {
filePart = request.getPart("uploadImageForNewCustomerformId");
String fileNamer = getFileName(filePart);
// rest of code not shown here
2.) My view (Prime Faces 6.0 facelet):
<h:form id="newCustomerformId">
<!-- rest of code not shown -->
<p:commandButton type="submit" value="Create Customer"
icon="ui-icon-check"
actionListener="#{newCustomerBean.saveNewCustomer}"
update = "#form"
oncomplete="ajaxUploadFile();"/>
</h:form>
<h:form id="uploadImageForNewCustomerformId"
enctype="multipart/form-data">
<div id="dropzone">
<img id="librarypreview" src='' alt='library'
style="width: 280px; height: 160 px;" /> <select name="top5"
id="flist" size="5" onchange="previewFile()">
</select>
<output id="list"> </output>
</div>
<input id="fileInput" type="file" name = "file"></input>
<span id="uploadStatusId"></span>
</h:form>
3.) My Java Scipt function for ajax-uploading the file:
function ajaxUploadFile() {
var form = document.getElementById('uploadImageForNewCustomerformId');
if (form == null)
return;
var formData = new FormData(form);
for (var i = 0; i < fileList.length; i ++){
//append a File to the FormData object
formData.append("file", fileList[i], fileList[i].name);
}
var uploadStatusOutput = document.getElementById("uploadStatusId");
var request = new XMLHttpRequest();
request.open("POST", "/javakurs3-biliothek-jsf-mobile/fileUpload");
request.responseType = 'text';
request.onload = function(oEvent) {
if (request.readyState === request.DONE) {
if (request.status === 200) {
if (request.responseText == "OK") {
form.action = "/javakurs3-biliothek-jsf-mobile/pages/customers.jsf";
form.submit();
return;
}
}
uploadStatusOutput.innerHTML = "Error uploading image";
} // request.readyState === request.DONE
}; // function (oEvent)
request.send(formData);
};
I was finally was able to solve the problem. As BalusC correctly put it, I am not only doing a preview of the image using Java Script, but also uploading it using Java script. This caused confusion, as PrimeFaces supports an image preview and an image upload using their custom, own tag, as shown here .
p:fileUpload showcase
The problem using this p:fileUpload is that it has its own button for the image submission, or upload. However, I want to both submit my newly entered customer data AND upload the image using EXACTLY ONE button and button click.
The solution to my requirement is that I used the following code in my ImageUploadServlet
for (Part fPart : request.getParts()){
if (fPart.getName()!=null && fPart.getName().equals("file") && StringUtils.isNotEmpty(fPart.getSubmittedFileName())){
fileNamer = fPart.getSubmittedFileName();
filePart = fPart;
break;
}
}
instead of the code I mentioned in my question:
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
}
}
return null;
}
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
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.