How to use getParts in java to get only image parts? - java

I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support.
Here is my code:
Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div class="form-group">
<label>Name:</label> <input class="form-control" value="${product.name}" name="name" />
</div>
<div class="form-group">
<label>Price:</label> <input class="form-control" value="${product.price}" type="number" name="price" />
</div>
<div class="form-group">
<label>Quantity:</label> <input class="form-control" value="${product.quantity}" type="number" name="quantity" />
</div>
<div class="form-group">
<label>Image:</label> <input class="form-control" value="${product.image}" name="image" />
</div>
<div class="form-group">
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div class="form-group">
<label>Category</label>
<div class="checkbox">
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);

The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.

Related

Saving an image inserted by user in a folder under WEB-INF in a jsp project

I am trying to save an image inserted by an <input> field in a form by the user to a folder named imgs under the WEB-INF folder and store in the table column of the product the path of that photo so i can later display them in a products page for my online shop.
I don't know how to send the image to the java file (using jdbc server) so i can save it and also how i can save it. I have researched online but I have not fount what i am looking for. Below is my .jsp file.
<body>
<%
if(request.getParameter("btn") != null){
String name = request.getParameter("name");
String description = request.getParameter("description");
double price = Double.valueOf( request.getParameter("price"));
String brand = request.getParameter("brand");
String type = request.getParameter("type");
int quantity = Integer.parseInt( request.getParameter("quantity"));
File picture =
Client client = Client.create();
WebResource webResource =client.resource("...link.../"+name+"/"+description+"/"+price+"/"+brand+"/"+type+"/"+quantity+"/"+picture);
ClientResponse myresponse = webResource.accept("text/plain").get(ClientResponse.class);
}
%>
<div class="p-5" >
<h1 id="title" class="d-flex justify-content-center" style="font-size:4rem;">Edit your Profile</h1>
<form class="container " method="post">
<div class="form-row">
<div class="form-group col-6">
<label for="name">Product name:</label>
<input class="form-control" type="text" name="name"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="description">Description:</label>
<textarea class="form-control" name="description" cols="40" rows="5"></textarea><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-3">
<label for="price">Price:</label>
<input class="form-control" type="number" name="price"><br>
</div >
<div class="form-group col-6">
<label for="brand">Product brand:</label>
<input class="form-control" type="text" name="brand"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="type">Product type(running, walking, casual ,etc...):</label>
<input class="form-control" type="text" name="type"><br>
</div >
<div class="form-group col-6">
<label for="quantity">Available quantity:</label>
<input class="form-control" type="text" name="quantity"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="picture">Product picture:</label>
<input class="form-control" type="file" name="picture"><br>
</div >
</div>
<button type="submit" name="btn">Sign in</button>
</form>
</div>
</body>

Conversion of 3 files to user desired output using Angular and springboot

I'm trying to upload multiple files to springboot server from angular but I don't know why I'm getting error.But in postman the code is working fine and I'm able to upload files and output format.
I'm getting this error in browser
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: 'http://localhost:8080/file/Upload', ok: false, …}
Error in backend terminal:
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'fileN' is not present]
springboot restapi:
#postMapping(value="/Upload")
public ResponseEntity<List<String>> uploadFiles(#RequestParam ("fileN")List<MultipartFile> multipartFiles,#RequestParam("fileFormat")String id) throws IOException, FOPException, TransformerException{
List<String> filenames = new ArrayList<>();
try{
for(MultipartFile file : multipartFiles){
String filename = StringUtils.cleanPath(file.getOriginalFilename());
Path fileStorage = get(DIRECTORY, filename).toAbsolutePath().normalize();
copy(file.getInputStream(), fileStorage, REPLACE_EXISTING);
filenames.add(filename);
}
fileConversion.Convert(id);
}
catch (Exception e){
e.printStackTrace();
}
return ResponseEntity.ok().body(filenames);
user service:
constructor(private http: HttpClient){}
uploadFile(formData: FormData): Observable<any>{
const headerDist = {
'Access-Control-Allow-Origin': '*';
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'access-control-allow-credentials':'true'
'Content-Type': 'multipart/form data; boundary=Inflow'
}
const requestOptions = {
headers: new HttpHeaders(headerDist),
};
return this.http.post('http://localhost:8080/file/Upload',formData,requestOptions);
}
appcomponent:
onSubmit(){
const formData = new formData();
formData.append('fileN', this.angForm.get('file1').value);
formData.append('fileN', this.angForm.get('file2').value);
formData.append('fileN', this.angForm.get('file3').value);
formData.append('fileN', this.angForm.get('fileFormat').value);
this.userService.uploadFile(formData).subscribe (
(res) => console.log(res),
(err) => console.log(err)
)};
html:
<h2 id="zone" xmlns="http://www.w3.org/1999/html">File Conversions</h2>
<form [formGroup]="angForm" enctype="multipart/form-data" (ngSubmit)="onSubmit()" >
<div class="main">
<div class="classOne">
<div class="form-two">
<input type="file" class="file-input" formControlName="file1" id="ixml" value="" accept="xml/*" required (change)='uploadF($any($event.target).files)' #open>
<div class="file-upload">
<p class="para-tag">Input XML :</p>
<button mat-raised-button color="primary" class="upload-btn" (click)="open.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file1'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file1'].errors.required"></div>
</div>
<div class="classTwo">
<div class="form-two">
<input type="file" class="file-input" formControlName="file2" id="udtd" value="" accept="dtd/*" required (change)="uploadFile($event.target.files)"#ele>
<div class="file-upload">
<p class="para-tag">Upload DTD : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="ele.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file2'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file2'].errors.required"></div>
</div>
<div class="classThree">
<div class="form-two">
<input type="file" class="file-input" formControlName="file3" id="uxsl" value="" accept="xsl/*" required (change)="uploading($event.target.files);"#choose>
<div class="file-upload">
<p class="para-tag">Upload XSL : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="choose.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file3'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file3'].errors.required"></div>
</div>
<div class="classFour">
<p class="para-tag-two">Choose Your Output Format :</p>
<div>
<input type="radio" id="pdf" value="pdf" name="fileFormat" formControlName="fileFormat">
<label for="pdf">PDF</label><br>
<input type="radio" id="ps" value="ps" name="fileFormat" formControlName="fileFormat">
<label for="ps">PostScript</label><br>
<input type="radio" id="png" value="png" name="fileFormat" formControlName="fileFormat">
<label for="png">PNG</label><br>
<input type="radio" id="txt" value="txt" name="fileFormat" formControlName="fileFormat">
<label for="txt">Text</label><br>
<input type="radio" id="print" value="print" name="fileFormat" formControlName="fileFormat">
<label for="print">Print</label><br><br>
</div>
</div>
<div *ngIf="angForm.controls['fileFormat'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['fileFormat'].errors.required"></div>
</div>
<div class="submit">
<button style="width:100px;" type="submit" [disabled]="angForm.invalid" mat-raised-button color="warn"disabled="true" >Submit</button>
</div>
</div>
</form>

Encryption method for cuba platform

Cuba has its own backend system to add users.
Now I need to write a user registration in the front-end.
The Cuba version I am using is 6.9
I know that this version of encryption is SHA1 : https://doc.cuba-platform.com/manual-6.9/login.html
Now my question is : I don't know how to set the encrypted password to the database.
I create an entity through the Metadata
User user = metadata.create(User.class);
user.setPassword(passWord);
I'm not sure that's the best option but I used the following code:
#Inject
protected PasswordEncryption passwordEncryption;
...
user.setPassword(passwordEncryption.getPasswordHash(user.getId(), password));
I think you just need to create html file with this code:
<div class="span6">
<h3>Login</h3>
<div th:if="${(param.error != null)}">
<p>Invalid username / password</p>
</div>
<form id="f" name="f" method="POST" action="login">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div>
<div>
<label style="width: 80px" for="login">Login</label>
<input type="text" id="login" name="login" value=""/>
</div>
<div>
<label style="width: 80px" for="password">Password</label>
<input type="password" id="password" name="password" value=""/>
</div>
</div>
<button type="submit">Login</button>
</form>
</div>
and then Request it from Controller:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
if (PortalSessionProvider.getUserSession().isAuthenticated()) {
LoadContext l = new LoadContext(User.class);
l.setQueryString("select u from sec$User u");
model.addAttribute("users", dataService.loadList(l));
}
return "index";
}

Java/Spring/MultipartFile File-upload with AngularJS:DefaultHandlerExceptionResolver: MultipartFile param not present" Controller is getting the file

Spring-controller is getting the MultipartFile, but its still throwing
"DefaultHandlerExceptionResolver:186 - Handler execution resulted in exception: Required MultipartFile parameter 'txnFile' is not present"
This is causing AngularJS client call to fail with 400.
JAVA-Spring-Controller:
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public #ResponseBody Response uploadMultipleFileHandler(
#RequestParam("fileType") String fileType,
#RequestParam("fileEtx") String fileEtx,
#RequestParam("country") String country,
#RequestParam("network") String network,
#RequestParam("version") String version,
#RequestParam("txnDate") String txnDateStr,
#RequestParam("txnFile") MultipartFile txnFile,
#RequestParam("exceptionFile") MultipartFile exceptionFile){
Response response= null;
try {
Here, txnFile and exceptionFile is not null. Code runs file as well. But it still throws "DefaultHandlerExceptionResolver:186 - Handler execution resulted in exception: Required MultipartFile parameter 'txnFile' is not present"
Java-Spring-Config:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000" />
</bean>
HTML-AngularJS-Form:
<form method="POST" action="http://localhost:8080/recon-validation-tool/ctrl/core/uploadMultipleFile" enctype="multipart/form-data">
<fieldset>
<legend>Select Txn file:</legend>
<div class="form-group">
<label for="">Txn-file:</label>
<input type="file" file-model="txnFile"/>
</div>
</fieldset>
<fieldset>
<legend>Select Exec file:</legend>
<div class="form-group">
<label for="">Exec file:</label>
<input type="file" file-model="exceptionFile"/>
</div>
</fieldset>
<fieldset>
<legend>Please enter carrier details:</legend>
<div class="form-group">
<label for="txnDate">Date:</label>
<input type="date" name="txnDate" ng-model="formData.txnDate" value="2017-05-30">
</div>
<div class="form-group">
<label for="fileType">Type:</label>
<input type="text" name="fileType" ng-model="formData.fileType">
</div>
<div class="form-group">
<label for="fileEtx">Ext:</label>
<input type="text" name="fileEtx" ng-model="formData.fileEtx">
</div>
<div class="form-group">
<label for="country">country:</label>
<input type="text" name="country" ng-model="formData.country">
</div>
<div class="form-group">
<label for="country">network:</label>
<input type="text" name="network" ng-model="formData.network">
</div>
<div class="form-group">
<label for="version">version:</label>
<input type="text" name="version" ng-model="formData.version">
</div>
</fieldset>
<br>
<button ng-click="uploadFile()">Validate</button>
</form>
AngularJS-Controller:
controllerM.controller('HomeController', function($scope, $http, $location, $rootScope){
$scope.formData= {};
$scope.formData.fileEtx= "";
$scope.formData.fileType= "";
$scope.formData.country= "";
$scope.formData.network= "";
$scope.formData.version= "";
$scope.formData.txnDate= "";
$scope.uploadFile = function(){
var data = new FormData();
data.append('fileEtx', $scope.formData.fileEtx);
data.append('fileType', $scope.formData.fileType);
data.append('country', $scope.formData.country);
data.append('network', $scope.formData.network);
data.append('version', $scope.formData.version);
data.append('txnDate', $scope.formData.txnDate);
data.append('txnFile', $scope.txnFile);
data.append('exceptionFile', $scope.exceptionFile);
var uploadUrl = "http://localhost:8080/recon-validation-tool/ctrl/core/uploadMultipleFile";
$http.post(uploadUrl, data, {
headers: {'Content-Type': undefined},
transformRequest: angular.identity
})
.success(function(resp){
console.log(resp);
})
.error(function(resp){
console.log(resp);
});
};
});

How to navigate between html & jsp pages in spring

I have a Html page called kind.html inside the WEB-INF directory and an other jsp page called registration.jsp inside the WEB-INF folder. I need to put this registration.jsp page inside the WEB-INF directory so it cannot be accessible if a user attempts to get access to it by typing its URL. So my problem is how can i navigate from kind.html to registration.jsp with link called home I am newbie in this Thank you.
below is my code snippet and png file
kind.html..............................................
<li class='active'><a href='kind.html'><span>Home</span></a></li>
<li class='has-sub'><span>Register</span>
.............................registrationcontroller........................................
#RequestMapping(value="/registration",method = RequestMethod.POST)
public #ResponseBody
String firstRegistration(HttpServletRequest req,
HttpServletResponse response) {
response.setContentType("text/html");
RegistrationModel registrationModel = new RegistrationModel();
registrationModel.setFirstName(req.getParameter("first_name"));
System.out.println("controller " + req.getParameter("first_name") );
registrationModel.setLastName(req.getParameter("last_name"));
registrationModel.setPassword(req.getParameter("password"));
registrationModel.setEmailID(req.getParameter("email"));
System.out.println("controller email " + req.getParameter("email"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date = format.parse(req.getParameter("BirthDate"));
registrationModel.setDOB(date);
} catch (Exception e) {
e.printStackTrace();
}
String phoneno=req.getParameter("phoneNo");
Integer phoneNo = Integer.parseInt(phoneno);
System.out.println("phone no ...."+phoneNo);
registrationModel.setPhoneNo(phoneNo);
registrationModel.setGender(req.getParameter("gender"));
String age=req.getParameter("Age");
Long AGE = Long.parseLong(age);
registrationModel.setAge(AGE);
registrationModel.setAvtar(req.getParameter("Avtar"));
System.out.println("avtar"+ req.getParameter("Avtar"));
Address address = new Address();
address.setAddressline(req.getParameter("Full-Address"));
address.setCity(req.getParameter("city"));
address.setLandmark(req.getParameter("landmark"));
address.setState(req.getParameter("state"));
String zipCode =req.getParameter("Zipcode");
Long zipcode = Long.parseLong(zipCode);
address.setZipcode(zipcode);
registrationModel.setAddress(address);
registrationService.resgistration(registrationModel);
return "registration.jsp";
}
..........................registration.jsp.........................................................
<form action="registration" method="post">
<fieldset>
<legend>Register Form</legend>
<div>
<input type="text" name="first_name" placeholder="First Name" />
</div>
<div>
<input type="text" name="last_name" placeholder="Last Name" />
</div>
<div>
<input type="password" name="password" placeholder="Password" />
</div>
<div>
<input type="text" name="email" placeholder="Email" />
</div>
<div>
<input type="text" name="BirthDate" placeholder="BirthDate" />
</div>
<div>
<input type="number" name="Age" placeholder="Age" />
</div>
<div>
<select name="gender">
<option value="select">i am..</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select><br> <br>
</div>
<div>
<input type="number" name="phoneNo" placeholder="PhoneNo" />
</div>
<div>
<input type="text" name="Full-Address"
placeholder="Full-Address" />
</div>
<div>
<input type="text" name="landmark" placeholder="landmark" />
</div>
<div>
<input type="text" name="city" placeholder="city" />
</div>
<div>
<input type="text" name="state" placeholder="state" />
</div>
<div>
<input type="number" name="Zipcode" placeholder="Zipcode" />
</div>
<div>
<input type="file" name="Avtar" placeholder="Avtar" />
</div>
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>![folder structure of project][2]
1st to call your pages html is static so you can use mvc resources "" for it, for jsp you have to use ViewResolver for jstl use InternalResourceViewResolver in its configuration as :
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
then in your controller use
return "registration";
also you will need method to handle GET request and change below line
<li class='has-sub'><span>Register</span>
if you are using Spring boot you will find these configuration automated.

Categories

Resources