How to display stored images in Spring Boot using Angular 4? - java

I am using Spring Boot and Angular 4.
I have uploaded an image to the project location.
When I try to view the uploaded image, it is not displayed but an error is thrown.
How can I view the image?
ang.html:
<button type="button" class="button btn-info"
(click)='showInfo()'>ShowImages</button>
<div class="panel panel-primary">
<div class="panel-heading">List of Images</div>
<img [src]="fileUploads">
</div>
components.ts:
fileUploads: any;
sid: number = 1;
showInfo() {
this.drugservice.getFiles(this.sid).subscribe(data => {this.fileUploads = data, alert(data)}), err => {
console.log('Error Occured showInfo');
};
}
service.ts
getFiles(id: number): any {
return this.http.get(this.getFileuploadedURL+'/'+id, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'image/png' })
});
}
springBoot Controller:
#GetMapping(value = "/getUploadfiles/{id}")
#ResponseBody
public byte[] getImage(#PathVariable Integer id) throws IOException {
String filename = "01";
System.out.println("id : " + id);
File serverFile = new File(rootLocation + "\\" + filename + ".jpg");
System.out.println("serverFile : " + serverFile);
return Files.readAllBytes(serverFile.toPath());
}

Try updating your mapping in spring boot controller to:
#GetMapping(value = "/getUploadfiles/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
this will indicate that the returned object must be handled as a JPEG image.
In Angular create the required path to image and pass is to the img element, eg:
components.ts:
fileUrl = '/getUploadfiles/1';
ang.html:
<img [src]="fileUrl">

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

using servlet 3.0 I cannot get the actual FileName of an uploaded file

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

Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile] for property

I am saving an image file from jsp and renaming it in the controller
The problem is that same piece of code is working in one part of the controller and not working in another part of the controller
here is the jsp code which is same in both cases:-
<div class="form-group ">
<label for="photo">Photo:</label>
<form:input type="file" class="filestyle" path="studentPhoto"
id="studentPhoto" placeholder="Upload Photo"
required="required" />
</div>
Here is the part of the controller where it is working as expected:-
#RequestMapping(value = "/student", params = "add", method = RequestMethod.POST)
public String postAddStudent(#ModelAttribute #Valid Student student,
BindingResult result, Model model) throws IOException {
if (result.hasErrors()) {
System.out.println(result.getAllErrors().toString());
model.addAttribute("examination_names", ExaminationName.values());
ArrayList<Role> roles = new ArrayList<Role>();
roles.add(Role.STUDENT);
model.addAttribute("roles", roles);
return "student/add";
} else {
System.out.println("Inside postAddStudent");
System.out.println(student);
student = studentService.save(student);
String PROFILE_UPLOAD_LOCATION = servletContext.getRealPath("/")
+ File.separator + "resources" + File.separator
+ "student_images" + File.separator;
BufferedImage photo = ImageIO.read(new ByteArrayInputStream(student
.getStudentPhoto().getBytes()));
File destination = new File(PROFILE_UPLOAD_LOCATION
+ student.getId() + "_photo" + ".jpg");
ImageIO.write(photo, "jpg", destination);
return "redirect:student?id=" + student.getId();
}
}
Below is the part of controller where it is not working and says error:-
Failed to convert property value of type java.lang.String to required type org.springframework.web.multipart.MultipartFile for property studentPhoto; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile] for property studentPhoto: no matching editors or conversion strategy found
ControllerCode
#RequestMapping(value = "/examForm", params = "edit", method = RequestMethod.POST)
public String postEditExamForm(#ModelAttribute #Valid Student student,
BindingResult result, Model model) throws IOException {
String PROFILE_UPLOAD_LOCATION = servletContext.getRealPath("/")
+ File.separator + "resources" + File.separator
+ "student_images" + File.separator;
if (result.hasErrors()) {
model.addAttribute("flags", Flag.values());
return "examForm/edit";
} else {
Student updatedStudent = studentService.findOne(student.getId());
updatedStudent.setDisqualifiedDescription(student
.getDisqualifiedDescription());
student = studentService.update(updatedStudent);
BufferedImage photo = ImageIO.read(new ByteArrayInputStream(student
.getStudentPhoto().getBytes()));
File destination = new File(PROFILE_UPLOAD_LOCATION
+ student.getId() + "_photo" + ".jpg");
ImageIO.write(photo, "jpg", destination);
return "redirect:examForm?id=" + updatedStudent.getId();
}
}
You were missing enctype="multipart/form-data" in your <form:form...> tag.
Since your form doesn't had enctype="multipart/form-data" spring was taking <form:input type="file".. as String and throwing error when it cannot convert String to MultipartFile for studentPhoto of type MultipartFile in Student class.
Here's the complete source code.

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.

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