Drag Drop file upload with AngularJS and Spring Rest - java

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.

Related

Although I wrote 'enctype="multipart/form-data', ERROR 'Current request is not a multipart request' happen

I am implementing the file upload function.
When I upload a file, it shows what I uploaded, puts in the contents, and posts.
By the way, there was a problem below while uploading the files.
While trying to find a solution, many people asked me to add enctype="multipart/form-data but I added that one earlier.
And yet I don't understand that kind of error.
error
2021-07-30 23:08:21.239 ERROR 20744 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause
front
<template>
<div class="scale">
<button><b-icon-arrow-left></b-icon-arrow-left></button><span>게시글 생성하기</span>
<form enctype="multipart/form-data" method="post" >
<div class="d-flex flex-row">
<button style="display:inline-block; margin-right:5%; margin-left:2%" #click.prevent="clickInputTag()" id='addimage'><b-icon-plus class="h1"></b-icon-plus></button>
<input hidden ref="plus" name="file" id="file" type="file" accept="image/*" #change.prevent="uploadImage($event)" multiple>
<div id="image_container"></div>
</div>
<div>
<b-textarea v-model="content" placeholder="Tall textarea" rows="8"></b-textarea>
<b-button #click="articleCreate()" >전송</b-button>
</div>
</form>
</div>
</template>
import axios from 'axios'
export default {
name:'ArticleCreate',
data(){
return{
content:"",
files: new FormData(),
}
},
methods:{
clickInputTag() {
this.$refs['plus'].click()
},
uploadImage(event) {
console.log(event.target.files)
const photoFile = document.getElementById("file")
this.files.append("file", photoFile.files[0]);
for (var image of event.target.files) {
var reader = new FileReader();
reader.onload = function(event)
{
var img = document.createElement("img");
img.setAttribute("src", event.target.result);
img.setAttribute("width","25%");
document.querySelector("div#image_container").appendChild(img);
};
reader.readAsDataURL(image);
}
console.log(this.files, typeof this.files)
},
articleCreate(){
axios({
url:'http://127.0.0.1:8080/article',
method:'post',
headers: {
'x-access-token': `${localStorage.getItem('token')}`,
},
params: {
content: this.content,
files: this.files,
}
})
.then(res=>{
this.$router.push({ name:'article'})
console.log(res.data)
console.log(this.files)
})
.catch(err=>{
console.log(`${localStorage.getItem('token')}`)
console.log(this.files)
console.log(this.content)
console.log(err)
})
},
}
}
back
#PostMapping("/article")
#ApiOperation(value = "게시글 작성")
public Object postArticle(#RequestParam String content, #RequestParam(required = true) List<MultipartFile> files) throws IOException {
Authentication user = SecurityContextHolder.getContext().getAuthentication();
ResponseEntity response = null;
if(user.getPrincipal() == "anonymousUser"){
response = new ResponseEntity<>("Fail", HttpStatus.UNAUTHORIZED);
return response;
}else {
UserDetails user2 = (UserDetails) user.getPrincipal();
Optional<User> userOpt = userDao.findByEmail(user2.getUsername());
Long articleId = articleDao.save(Article.builder()
.articleid(null)
.id(userOpt.get().getUid())
.createdtime(null)
.updatedtime(null)
.review(content)
.build()
).getArticleid();
List<String> pathName = saveFiles(files);
System.out.println(pathName.get(0));
for(int i = 0; i < files.size(); ++i) {
imageDao.save(Image.builder()
.imageid(null)
.articleid(articleId)
.imgURL(pathName.get(i))
.build()
);
}
response = new ResponseEntity<>("게시글 작성 완료", HttpStatus.OK);
return response;
}
}
Try adding content-type: multipart/form-data in header of your axios call.
headers: {
'x-access-token': `${localStorage.getItem('token')}`,
'content-type': 'multipart/form-data'
}
Also your axios post data should be in FormData type
var dataBody = new FormData();
dataBody .append('content', this.content);
dataBody .append('files', this.files);
change params to data and set it to dataBody
axios({
url:'http://127.0.0.1:8080/article',
method:'post',
headers: {
'x-access-token': `${localStorage.getItem('token')}`,
'content-type': 'multipart/form-data'
},
data: dataBody
}
Finally, at your backend:
Add consumes = { MediaType.MULTIPART_FORM_DATA_VALUE } in #PostMapping.
Replace #RequestParams with #RequestPart.
#PostMapping("/article", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
#ApiOperation(value = "게시글 작성")
public Object postArticle(#RequestPart String content, #RequestPart(required = true) List<MultipartFile> files)

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);
}
});
});

Upload file to a server with jquery and java

Im doing a webapp to upload files to a server.
I have this form in my view:
<body>
<form>
<input id="file" type="file" name="file">
<input id="send" value="Upload" type="button" />
</form>
</body>
And i send the file with jquery and ajax:
var form = new FormData();
form.append('file', $("#file")[0].files[0]);
$.ajax({
type: 'POST',
url: 'http://localhost:8080/UploadMotion/upload',
cache: false,
contentType: false,
processData: false,
data: form,
success: function (data) {
alert("Funciono");
},
error: function () {
alert("Fallo");
}
});
The jquery looks like correct, because the value of the file is sent correctly in the form var.
I send this data to my controller, but I'm not receiving the correct file. I'm receiving a temporal file, with this format:
...\...\AppData\Local\Temp\upload_c72334c_14b9858dd1d__8000_00000004.tmp
This is the code of the controller:
public Render upload(File file) throws IOException{
String folderName = "C:\\Users\\Inma\\Documents\\MisDescargas";
String token = UUID.randomUUID().toString();
String fileName = folderName+ File.separator + token;
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(fileName);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
return renderJSON("token",token);
}
I use webmotion, a framework to develop web applications.
This is the mapping file:
[config]
package.views=WEB-INF/views
package.actions=com.vincle.actions
[actions]
GET / view:index.jsp
POST /upload MainController.upload
GET /download MainController.download
The networks screen shows this: http://postimg.org/image/lguc3q1ex/
When I try to create the FileInputStream to copy this file to my server, I get the exception FileNotFound exception, because this file doesn't exist.
What is the problem? Why don't I recieve the correct file?
Thanks in advance

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);
}

How to send parameters to portlet use jquery

I have a form on my jsp page. In this form i choose a file (zip archive) and after click submmit call servlet to upload this file. For file upload im use Apache Commons FileUlpoad library. After upload im unzip archive. Them i do redict to this jsp.
jsp code:
<form action="Upload_Servlet" method="post" enctype="multipart/form-data">
<div id="up">
<input id="fileUpload1" type="file" name="filename1"value="Browse..."/>
</div>
<div>
<input id="btnSubmit" type="submit" value="Загрузить">
<input type="button" id="del" onclick="deleting()" value="Удалить">
</div>
</form>
servlet code:
public class uploadfile extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
System.out.println(response.getCharacterEncoding());
response.setCharacterEncoding("UTF-8");
System.out.println(response.getCharacterEncoding());
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("wtpwebapps<br/>");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
writer.println("<HTML>");
writer.println("<HEAD <TITLE> Upload4 </TITLE> </HEAD>");
writer.println("<BODY>");
writer.println("<FORM action = \"Upload_Servlet\" method = \"post\" enctype = \"multipart/form-data\">");
writer.println("<INPUT type = file name = ufile>");
writer.println("<INPUT type = submit value = \"Attach\">");
writer.println("<h1>its not multipart</h1>");
writer.println("</FORM>");
writer.println("</BODY>");
writer.println("</HTML>");
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list=null;
String mifpath= "1";
String path = " ";
String mif = " ";
String from = "\\\\";
String to ="/";
String error="";
try{
list = upload.parseRequest(request);
Iterator<FileItem> it = list.iterator();
response.setContentType("text/html");
while ( it.hasNext() )
{
FileItem item = (FileItem) it.next();
File disk = new File("C:/uploaded_files/"+item.getName());
path = disk.toString();
String code = new String(path.substring(path.lastIndexOf("."), path.length()).getBytes("ISO-8859-1"),"utf-8");
if (code.equalsIgnoreCase(".zip"))
{
mifpath=path;
mif = mifpath.replaceAll(from, to);
item.write(disk);
error=unzip.unpack(mif, "C:/uploaded_files");
}
else
{
error = "Выбранный файл не является архивом zip";
}
}
}
catch ( Exception e ) {
log( "Upload Error" , e);
}
request.setAttribute("error", error);
request.getRequestDispatcher("/Home.jsp").forward(request, response);
// String redictedURL="http://localhost:8080/redicted_test/Home.jsp";
// response.sendRedirect(redictedURL);
writer.close();
}
}
Now i want to do this on the portal. Its mean that i dont want to reload my jsp after I upload a file. So i have to use Jquery. And i have some questions:
How to submit form to use jquery in my case?
My servlet code will be work in portlet?
How to send parametrs to jps from portlet?
Using Jquery it can be done easily:
Set a click event on the submit button (or on the form submit).
Post data to servlet:
$.ajax({
url : base_url + 'Upload_Servlet',
type : "post",
data:$('form').serialize(),
cache : false,
success : function(data) {
//do some stuff
},
error : function(xhr, status, err) {
//do error stuff
},
timeout : 3000
});
//End ajax call
After the servlet is done, just use the response writer to write an aswer back (If it contains a lot of data, I'd recommend sending a response in the form of json, see here) and then the success callback is called and you can do whatever you like with this data.
IMPORTANT: Since you are submitting a form, you need to use e.preventDefault() so the form will not be actually submitted but rather be handeled by your ajax.

Categories

Resources