Copying files to folder - java

I have this:
In addMusic.jsp:
<form method="post" action="Handler" enctype="multipart/form-data">
<div class="form-group">
<label>Musica:</label>
<input type="text" class="form-control" name="add_musica_nome" placeholder="Nome Musica">
</div>
<div class="form-group">
<label>Localização:</label>
<input type="file" class="form-control" name="add_musica_path" accept="audio/*">
</div>
<div class="form-group">
<label>Ano:</label>
<input type="text" class="form-control" name="add_musica_ano" pattern="[0-9]{4,4}">
</div>
<div class="form-group">
<input type="hidden" name="logica" id="logica" value="SMusica"/>
<input type="hidden" name="acao" id="acao" value="addMusica"/>
<input class="btn btn-success" type="submit" value="Inserir" name="inserir"/>
</div>
</form>
In Handler:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String parametro = request.getParameter("logica"); // Recebe como parametro do jsp, qual a class do service que
// irá atuar
String nomeDaClasse = "services." + parametro; // Nome da Classe
try {
Class<?> classe = Class.forName(nomeDaClasse);
Logica logica = (Logica) classe.newInstance();
String pagina = logica.executa(request, response);
request.getRequestDispatcher(pagina).forward(request, response);
} catch (Exception e) {
throw new ServletException("A lógica causou uma exceção", e);
}
}
and in SMusica:
final String Dest = "/data/";
public void addMusica(String musica_nome, Part musica, String ano) throws IOException {
String fileName = Paths.get(musica.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
try {
File music = new File(fileName);
System.out.println("Path: " + music.getAbsolutePath());
if (music.renameTo(new File(Dest + music.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {
if (req.getParameter("acao").equals("addMusica")) {
addMusica(req.getParameter("add_musica_nome"), req.getPart("add_musica_path"),
req.getParameter("add_musica_ano"));
}
return "/index.jsp";
}
And i made a print of absolutePath of music(File) and it returns C:\Users\Fabio\Desktop\eclipse\ProfJam_-_Mortalhas.mp3, not the real path.
My question is how can i get the real path of the file?

There is a method in path called
Path _rp = p.toRealPath();
Maybe you Can search in this direction

Related

HTML form parameter are all null

I have to create a form for update some user profile data. I develop this html form but when I submit and I try to get request parameters they all result null.
The form is filled with actual data and then you can modify them refilling with the new one.
Thanks
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="all" href="../CSS/style.css" th:href="#{.../CSS/style.css}"/>
<script type="text/javascript" src="../js/signup.js" th:src="#{/js/signup.js}" defer> </script>
<script type="text/javascript" src="../js/updateProfile.js" th:src="#{/js/updateProfile.js}" defer> </script>
<script type="text/javascript" th:src="#{/js/loadimage.js}" defer ></script> <!--defer fa eseguire js dopo il parsing di html-->
</head>
<body>
<div class="container">
<h1>Profilo Utente</h1>
<div class="form">
<form action="updateprofile" method="post" enctype="multipart/form-data" onsubmit="return formValidation()">
<p>
<label for="username">Username: </label><br>
<input type="text" id="username" name="username" th:attr="value=${session.user.username}" required/><br>
</p>
<p>
<label for="email">Mail: </label><br>
<input type="email" id="email" name="email" th:attr="value=${session.user.email}" required/><br>
</p>
<p>
<label for="password">Password: </label><br>
<input type="password" id="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Deve contenere almeno 8 caratteri di cui un numero, una lettera maiuscola e una lettera minuscola." /><br>
</p>
<p>
<label id="text-password-confirm" for="password-confirm">Reinserisci password: </label><br>
<input type="password" id="password-confirm" />
</p>
<p id="password-message" class="error-message"></p>
<p>
Tipo di utente:<br>
<input type="radio" name="usertype" id="manager" value="manager" th:checked="${session.user.isManager!=null && session.user.isManager}" required/>
<label for="manager">Manager</label><br>
<input type="radio" name="usertype" id="worker" value="worker" th:checked="${session.user.isManager!= null && !session.user.isManager}" checked required/>
<label for="worker">Worker</label><br>
</p>
<div id="worker-data">
<p>
<label for="exp">Exp level:</label><br>
<select name="exp" id="exp">
<option value="" disabled selected>Exp level</option>
<option value="LOW" th:selected="${session.user.exp == 'LOW'}">LOW</option>
<option value="MEDIUM" th:selected="${session.user.exp == 'MEDIUM'}">MEDIUM</option>
<option value="HIGH" th:selected="${session.user.exp == 'HIGH'}">HIGH</option>
</select><br>
</p>
<p>
<label for="photo">Profile photo</label><br>
<div id="container"style="position: relative; width:300px;">
<canvas id="canvas_background" width="300px" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
<input type="file" name="photo" id="photo" accept="image/*"/><br>
</div>
<!-- TODO: Rivedere i messaggi di errore inseriti -->
<span class="error-message" th:if="${session.signupfailed}">Salvataggio non riuscito</span>
<p>
<input id="buttonModifica" type="button" value="Modifica" />
<input id="buttonAnnulla" type="reset" value="Annulla" />
<input id="buttonAggiorna" type="submit" value="Aggiorna" />
</p>
</form>
</div>
</div>
</body>
</html>
This is java code of the Update Profile controller
public class UpdateProfile extends AbstractServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("sessionUser");
if (user != null && user.isValid()){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
boolean isManager = request.getParameter("usertype").equals("manager");
String photo;
Level exp;
if (isManager) {
photo = null;
exp = null;
} else {
photo = ImageEncoder.encodeImage(request.getPart("photo"));
exp = Level.valueOf(request.getParameter("exp"));
}
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setIsManager(isManager);
user.setPhoto(photo);
user.setExp(exp);
}
try {
UserDAO userDAO = new UserDAO(connection);
userDAO.updateProfile(user);
success=true;
} catch (SQLException e) {
}
}
This are javascript code included in signup.jsp:
function formValidation(e) {
var confirm_password = document.getElementById("password-confirm");
if (comparePassword(confirm_password, "Le due password non coincidono") ) {
/*e.preventDefault();
window.history.back();*/
return true;
}
return false;
}
function comparePassword(inputtext, alertMsg){
var password = document.getElementById("password");
if(inputtext.value != password.value) {
document.getElementById('password-message').innerText = alertMsg;
inputtext.focus();
return false;
} else {
return true;
}
}
This is javascript code included in updateProfile.jsp:
var username = document.getElementById("username");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordConfirm = document.getElementById("password-confirm");
var radioWorker = document.getElementById("worker");
var radioManager = document.getElementById("manager");
var exp = document.getElementById("exp");
var photo = document.getElementById("photo");
var buttonModifica = document.getElementById("buttonModifica");
var buttonAnnulla = document.getElementById("buttonAnnulla");
var buttonAggiorna = document.getElementById("buttonAggiorna");
function init() {
username.readOnly=true;
email.readOnly=true;
password.readOnly=true;
passwordConfirm.hidden=true;
radioManager.disabled=true;
radioWorker.disabled=true;
exp.disabled=true;
photo.disabled=true;
buttonAnnulla.hidden=true;
buttonAggiorna.hidden=true;
buttonModifica.addEventListener("click", abilitaModifica)
password.addEventListener("change", verificaPassword)
}
function abilitaModifica() {
email.readOnly=false;
password.readOnly=false;
exp.disabled=false;
photo.disabled=false;
buttonAnnulla.hidden=false;
buttonAggiorna.hidden=false;
buttonModifica.hidden=true;
}
function verificaPassword() {
passwordConfirm.hidden=false;
}
init();
try to update your servlet code with this one..
#WebServlet(
name = "UpdateProfile",
urlPatterns = {"/updateprofile"})
public class UpdateProfile extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("sessionUser");
if (user != null && user.isValid()){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
boolean isManager = request.getParameter("usertype").equals("manager");
String photo;
Level exp;
if (isManager) {
photo = null;
exp = null;
} else {
photo = ImageEncoder.encodeImage(request.getPart("photo"));
exp = Level.valueOf(request.getParameter("exp"));
}
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setIsManager(isManager);
user.setPhoto(photo);
user.setExp(exp);
}
try {
UserDAO userDAO = new UserDAO(connection);
userDAO.updateProfile(user);
success=true;
} catch (SQLException e) {
}
}
}

How to get a value from JSP's drop down into a servlet?

I have a drop down list in a JSP which I am reading the values from and pass it into my servlet to perform actions based on the value received.
Below is my JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="getdata.do" method="post">
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</div>
</div>
<hr class="colorgraph">
<div class="row">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</div>
</form>
</body>
</html>
I gave the drop down list an ID: reportSelection
In my servlet class, I tried to read it as below:
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
String message;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In POST Method");
getTableColumn gt = new getTableColumn();
String issue = request.getParameter("reportSelection");
System.out.println("Drop Down Message: " + issue);
try {
System.out.println("In Try");
if (issue.equals("Latency")) {
message = gt.cruise("latency");
} else if (issue.equals("DataQuality")) {
message = gt.cruise("DataQuality");
System.out.println("Data quality");
} else if (issue.equals("Outage")) {
message = gt.cruise("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I also printed the values of it just to see I am receiving any values from it.
But once I click on submit button, I see null pointer exception as
String issue = request.getParameter("reportSelection");
is receiving NULL from JSP
Could anyone let me know what is the mistake I am doing here & how do I correct it ?

isMultipartContent(request) is not working. I dont know what is happening, it should return true but it is returning false

I am using this code to upload a file(image) in a web application using jsp. And here in this code isMultipartContent(request) should return true but it returns false. I am not getting what is wrong.
<form class="form-contact contact_form" method="post" id="contactForm" novalidate="novalidate" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input class="form-control" name="ff_ctype" id="ctype" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Course Type'" placeholder = 'Course Type'>
</div>
</div>
<div class="col-12">
<div class="form-group">
<input name="cupload" id="cupload" type="file">
</div>
</div>
</div>
<div class="form-group mt-3">
<button type="submit" name="up_btn" value="submit" class="button button-contactForm btn_1">UPLOAD</button>
</div>
</form>
<%
String ctype="", cimage="", path="";
boolean successful=true;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
}
catch (FileUploadException e) {
e.printStackTrace();
}
for(FileItem myitem:items) {
if (myitem.isFormField()) {
String itemName1 = myitem.getFieldName();
String value=myitem.getString();
if(itemName1.equals("ff_ctype")) //control's name - textbox name
{
ctype=value;
}
}
else {
String type=myitem.getContentType();
long size=myitem.getSize()/1024; //kbytes
if(size==0) {
cimage="default.png";
}
else if((type.equals("image/pjpeg")
|| type.equals("image/jpeg")
|| type.equals("image/png")
|| type.equals("image/x-png")
|| type.equals("image/gif"))
&& size<400)
{
cimage=new java.util.Date().getTime()+myitem.getName();
path=config.getServletContext().getRealPath("/") + "uploads\\" + cimage;
File savefile=new File(path);
myitem.write(savefile);
}
else {
successful=false;
out.print("Sorry only pictures of less than 400kb are allowed to upload");
}
}
}
if(successful==true) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection MyConnection=DriverManager.getConnection(PATH + PLACE, USERNAME, PASSWORD);
try {
String q1="insert into coursetypes(ctype, cimage) values(?,?)";
PreparedStatement insertvalues=MyConnection.prepareStatement(q1);
insertvalues.setString(1, ctype);
insertvalues.setString(2, cimage);
if(insertvalues.executeUpdate()==1) {
out.print("Image Uploaded Successfully");
}
else {
out.print("Error occured");
}
}
catch(Exception e) {
out.print("Error in query due to: " + e.getMessage());
}
}
catch(Exception e) {
out.print("Error in connection due to: "+e.getMessage());
}
}
}
}
%>
There are no error messages.
This code should upload the file in uploads folder in my project but its very first step is going wrong, i.e., isMultipartContent(request) is returning false
My mistake was i used form method='get'. But multipart does not work with get method. Because, to my knowledge, as the image cannot be displayed on addressbar so this does not work. All the code displayed here is perfectly working.
The wrong code was:-
<form method="get">
The right way is:-
<form method="post">
After this it was working perfectly fine.

how to get multiple file names in database columns at a time ? i write a code which is uploading multiple files

I am using servlets in which servlet is uploading multiple files in folder at a time but it did not get all file names in database columns could any one help me in code how to get all file names in columns at a time which are uploaded by servlet
There is only one file name i get in database column like 20190416070203.192dellxps15.jpg but i want multiple file names in columns which are users uploaded like
20190416070203.192dellxps15.jpg
20190416070203.199HuaweiMAtebookXpro.jpg
20190416070203.207s10plus.jpg
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("page");
if (page == null) {
request.getRequestDispatcher("admin/login.jsp").forward(request, response);
;
} else {
doPost(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("page");
if (page.equals("add_product")) {
String appPath = "C:/Users/zaid/eclipse-workspace/Ecommerce-shopping/WebContent/";
String savePath = appPath + File.separator + SAVE_DIR;
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
Part part1 = request.getPart("file");
String fileName1 = extractFileName(part1);
final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
final Calendar c = Calendar.getInstance();
c.add(Calendar.MILLISECOND, 1);
String daformat=df.format(c.getTime());
for (Part part : request.getParts()) {
String fileName =extractFileName(part);
// refines the fileName in case it is an absolute path
if (fileName != null && !"".equals(fileName)) {
fileName = new File(fileName).getName();
part.write(savePath + File.separator +""+daformat+""+fileName);
}
}
request.setAttribute("message", "Upload has been done successfully!");
String name = request.getParameter("name");
String price = request.getParameter("price");
String category = request.getParameter("category");
String featured = request.getParameter("featured");
String image = request.getParameter("image");
Product p = new Product();
p.setName(name);
p.setPrice(price);
p.setCategory(category);
p.setFeatured(featured);
p.setImage("img/"+image);
DB account = new DB();
try {
account.addProduct(p);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Product added Successfully", "Info", JOptionPane.INFORMATION_MESSAGE);
request.getRequestDispatcher("admin/index.jsp").forward(request, response);
}
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}
}
//////////////// jsp ////////////////////////
<div class="signup-header">
<h2>Add Product</h2>
</div>
<form method="post" action="admin" enctype="multipart/form-data" >
<input type="hidden" name="page" value="add_product" >
<font color="#F24638"><c:out value="${message }"></c:out></font>
<div class="signup-group">
<label>Name</label>
<input type="text" name="name" placeholder="product name goes here" required>
</div>
<div class="signup-group">
<label>Price</label>
<input type="text" name="price" placeholder="product price" required>
</div>
<div class="signup-group">
<label>Category</label>
<input type="text" name="category" placeholder="product category" required>
</div>
<div class="signup-group">
<label>Featured</label>
<input type="text" name="featured" placeholder="yes/no" required>
</div>
<div class="signup-group">
<label for="fileupload"> Select an image to upload</label>
<input type="file" name="file" required multiple><br>
</div>
<div class="signup-group">
<input type="submit" value="Add Product">
</div>
</form>
<footer style="position: relative;top:60px; left: 0;bottom: 0;width: 100%; height:30%">
<div class="footer"> © 2018 Copyright:
Zoats.com
</div>
</footer>
how to get multiple images names in columns at a time in database columns with same user id like using single request in servlet.
user111 : 20190416070203.192dellxps15.jpg
user111 : 20190416070203.199HuaweiMAtebookXpro.jpg
user111 : 20190416070203.207s10plus.jpg
You can create one String list and add file names in that list. and convert that String list to comma separated String while storing it in DB
List<String> fileNames = new ArrayList<>();
for (Part part : request.getParts()) {
String fileName =extractFileName(part);
// refines the fileName in case it is an absolute path
if (fileName != null && !"".equals(fileName)) {
fileName = new File(fileName).getName();
part.write(savePath + File.separator +""+daformat+""+fileName);
fileNAmes.add(fileName);
}
}
request.setAttribute("message", "Upload has been done successfully!");
String name = request.getParameter("name");
String price = request.getParameter("price");
String category = request.getParameter("category");
String featured = request.getParameter("featured");
String image = request.getParameter("image");
Product p = new Product();
p.setName(name);
p.setPrice(price);
p.setCategory(category);
p.setFeatured(featured);
p.setImage(StringUtils.join(fileNames , ','));
import StringUtils from Apache Commons
import org.apache.commons.lang3.StringUtils
You should put the account.addProduct(p); into the for loop, that iterates through all the attachments.
Dhrumil Patel here is my jsp file in which i retrieve images using jstl `
<tr>
<td style="width: 50px;"><c:out value="${row.id }"></c:out></td>
<td style="width: 100px;"><c:out value="${row.name }"></c:out></td>
<td style="width: 100px;"><c:out value="${row.price }"></c:out></td>
<td style="width: 100px;"><c:out value="${row.category}"/></td>
<td style="width: 100px;"><img src="${row.image}" height="100" width="150" ></td>
<td style="width: 100px;">edit ||
delete</td>
</tr>
</table>
</c:forEach>`
and here is db class code
public Product fetchProduct(String id) throws SQLException {
dbConnect();
String sql = "select * from product where id=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
ResultSet rst = pstmt.executeQuery();
Product p = new Product();
while(rst.next()){
p.setId(rst.getInt("id"));
p.setName(rst.getString("name"));
p.setPrice(rst.getString("price"));
p.setCategory(rst.getString("category"));
p.setFeatured(rst.getString("featured"));
p.setImage(rst.getString("image"));
}
dbClose();
return p;
}

multipart form-data not working properly

In My JSP page I have three seperating forms with enctype ="multipart/form-data". On each of these forms I am uploading a file.
The first form is uploading the file correctly with type as application/pdf. But, the remaining two forms uploading the files as application/octet-stream.
The code as follows
<div id="form1" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form1" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
<div id="form2" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form2" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
<div id="form3" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form3" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
My Servlet code as
#MultipartConfig(maxFileSize = 16177215)
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String action = request.getParameter("action");
if(action.equals("form1"))
{
Part filePart = request.getPart("file");
if (filePart != null)
{
System.out.println("File Parts Not Null");
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
System.out.println("File name is : "+filename);
inputStream = filePart.getInputStream();
}
}
if(action.equals("form2"))
{
Part filePart = request.getPart("file");
if (filePart != null)
{
System.out.println("File Parts Not Null");
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
System.out.println("File name is : "+filename);
inputStream = filePart.getInputStream();
}
}

Categories

Resources