i want to get dropdown values in my program in order to merge the string to my file path so that the path will change dynamically according to user input.iam new to apache commoms,before i was using o'reilly api.
here is my code :
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
{
//FileItem f1;
String d1= request.getParameter("sel1");
String d2=request.getParameter("sel2");
String d3="/home/adapco/Desktop/output";
String conc=d3+"/"+d1+"/"+d2+"/";
filePath=(new StringBuilder()).append(conc).toString();
// filePath="/home/adapco/Desktop/output/";
isMultipart = ServletFileUpload.isMultipartContent(request);
}
i tried to debug and i am getting the wright file path but while proceeding further,the fileItems shows size=0 and and it is not entering the loop because of size0.
filePath="/home/adapco/Desktop/output/";
if i pass the upload path to the filePath it works fine.
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>"+filePath);
}
my html :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="upload" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<br />
<select name="sel1">
<option label ="1">aerospace</option>
<option label ="2">automotive</option>
</select>
<select name="sel2">
<option label="1">internal</option>
<option label="2">demo</option>
</select>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
The request.getParameter() calls should be removed. They are causing that the request body is parsed before Apache Commons FileUpload can parse it. The request.getParameter() should not be used on multipart/form-data requests.
You need to collect normal form fields in the else of your if (!fi.isFormField()).
if (!fi.isFormField()) {
// Collect uploaded files.
}
else {
// Collect normal form fields.
}
See also FileUpload User Guide and this answer.
Related
I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?
When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?
1) Below is my form excerpt. At the bottom lines I try to upload the file.
<body>
<form method='post' enctype="multipart/form-data" action="/hard">
{{csrf_field()}}
<section>
<br>
<legend><i><b> Complete Data Below</b></i></legend>
<br>
</section>
<section>
Choose program:
<select name="sc" id="xaos">
<optgroup label="postgraduates">
#foreach($transport as $y)
<option value="{{$y->object_id}}">{{$y->object_name}}</option>
#endforeach
</optgroup>
</select>
</section>
<br>
<section>
ID number:
<input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">
</section>
<br>
<section>
Select Language:
<select name="language" id="lang">
<option value="GR"> Greek</option>
<option value="EN"> English</option>
</select>
</section>
<br>
<section>
<label for="upload-file">select csv file</label>
<input type="file" name="upload-file">
</div>
<input type='submit' name='upload' value="Submit!">
</section>
</form>
<br>
<br>
</body>
2) And below is my controller code excerpt which handles file imported.
public function job(Request $p)
{
$a1 = $p -> get('sc');
$a2 = $p -> get('am');
$a3 = $p -> get('language');
$f_rownum = 0;
if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)
{
while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
{
$ac1=$data[0];
$ac2=iconv("Windows-1253", "UTF-8", $data[1]);
$ac3=iconv("Windows-1253", "UTF-8", $data[2]);
$ac4=iconv("Windows-1253", "UTF-8", $data[3]);
$ac5=$data[4];
...............
According to Laravel documentation you can store your csv file into the storage like this:
public function storeFile(Request $request)
{
$path = $request->file('upload-file')->store('{directoryName}');
return $path;
}
The above code store your file in storage and returns tha path which you can save it into your DB.
For retrieving the file, you can use this code if you want to force user to download the file:
return Storage::download('{pathWhichYouSavedInDB}');
or you can retrieve the content of the file by using this code:
$contents = Storage::get('{pathWhichYouSavedInDB}');
[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:
$url = Storage::url('file.jpg');
Or you can not to use fopen at all and just use the $contents which you already retrieved with
$contents = Storage::get('{pathWhichYouSavedInDB}');
I have a table with 3 columns.Last column has 4 radio buttons in each row.I am not able to fetch all the values of radio buttons checked after submitting the form.I always get only one value which is the value of radio button checked in the first row.
Here is the code of jsp page:
<form action = "SaveData" method = "POST" target = "_blank">
<h1>LIST</h1>
<%
try {
/* Create string of connection url within specified format with machine
name, port number and database name. Here machine name id localhost and
database name is student. */
String connectionURL = "jdbc:mysql://localhost:3306/sample";
// declare a connection by using Connection interface
Connection connection = null;
/* declare object of Statement interface that is used for executing sql
statements. */
Statement statement = null;
// declare a resultset that uses as a table for output data from tha table.
ResultSet rs = null;
// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters
of string type connection url, user name and password to connect to database.*/
connection = DriverManager.getConnection(connectionURL, "root", "password");
/* createStatement() is used for create statement object that is used for
sending sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from data";
rs = statement.executeQuery(QueryString);
%>
<table class="comparison-table">
<tr>
<th>LIST</th>
<th>Y/N</th>
<th>OPTIONS</th>
</tr>
<div>
<tr>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<form>
<input type="radio" name="option" value="a" checked> A
<input type="radio" name="option" value="b" >B
<input type="radio" name="option" value="c" > C
<input type="radio" name="option" value="d"> D
</form>
</td>
</tr>
</div>
<% } %>
<%
// close all the connections.
rs.close();
statement.close();
connection.close();
}
catch (Exception ex) {
%>
<%
out.println("Unable to connect to database."+ex);
}
%>
</table>
<button value="Submit" id="button">Submit</button>
</form>
Here is the Servlet code:
import javax.servlet.annotation.WebServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
//Extend HttpServlet class
#WebServlet("/SaveData")
public class SaveData extends HttpServlet {
// Method to handle GET method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"+
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
}
Output after submitting the form would be values of two parameters "choose" and "option". I get proper output for "choose" parameter ie. all the selected Yes/No options in a cloumn,whereas for "option" parameter i would get only the value of first row selected radio button ie if i select 'c' in the first row radio buttons only 'c' will be displayed with rest of the rows ignored.
Please help me out in fetching data of all the columns of the radio buttons selected in a String array.
I also want to fetch the value of "slist" which is from database using servlet. This is under td tag with name="list".
First you sould not nest form tag, remove the form tag before radio button.
From MDN web docs :
elements of type radio are generally used in radio
groups—collections of radio buttons describing a set of related
options. Only one radio button in a given group can be selected at the
same time.
You should add a variable to differentiate lines like this for example :
<tr>
<%! int lineNumber = 0 %>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<input type="radio" name="option<%= lineNumber %>" value="a" checked> A
<input type="radio" name="option<%= lineNumber %>" value="b" >B
<input type="radio" name="option<%= lineNumber %>" value="c" > C
<input type="radio" name="option<%= lineNumber %>" value="d"> D
</td>
</tr>
<% lineNumber++ %>
I need to save the image for an avatar.
Can anyone give me a simple code to save and retrieve image?
I need to:
Save image in folder
Save image name in DB
Finally retrieve on image tag; I have to do it by Query Builder
Form:
<form action="" method="post" role="form" multiple>
{{csrf_field()}}
<legend>Form Title</legend>
<div class="form-group">
<label for="">Your Image</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">save</button>
back
</form>
<img name="youravatar" src="">
</div>
Route:
Route::get('pic','avatarController#picshow');
Route::post('pic','avatarController#pic');
Controller:
I have the avatarController, but it is empty because I don't know what to do.
Database:
Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at
Other:
I found this code but I can't find out anything:
if ($request->hasFile('avatar')) {
$file = array('avatar' => Input::file('avatar'));
$destinationPath = '/'; // upload path
$extension = Input::file('avatar')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('avatar')->move($destinationPath, $fileName);
}
First, make sure you have the encrypt attribute in your form
<form action="#" method="post" enctype="multipart/form-data">
You can use something similar to this in your controller
public function save(Request $request)
{
$file = $request->file('file');
// rename your file
$name = $file->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($file));
return "file saved";
}
Yes, you should store the file route in your database as well.
Make sure you are using a consistent path for your images like
Finally you have to create a route to give public access to your image file, like so:
Route::get('images/{file}', function ($file) {
$public_path = public_path();
$url = $public_path . '/storage/' . $file;
// file exists ?
if (Storage::exists($archivo))
{
return response()->file($pathToFile);
}
//not found ?
abort(404);
});
Check the docs about Laravel Responses
I hope this gives you an Idea of what to do.
Upload Image in laravel 5.4
check if request has image
$request->hasFile('image')
OR
$request->file('image')->isValid()
Now Save Image
$request->inputname->store('folder-name') return image path 'folder name/created image name
$request->image->store('images')
Check if image exits
Storage::disk('local')->exists('image name');
Delete Image
Storage::delete('image');
This is my code
if ($request->hasFile('image') && $request->file('image')->isValid())
{
$path = $request->image->store('images');
if(!empty($path)){
$edit = Model::FindOrFail($id);
// Delete old image
$exists = Storage::disk('local')->exists($edit->image);
if($exists){
Storage::delete($edit->image);
}
$edit->image = $path;
$edit->save();
}
}
Reference
I have problem with send form without refresh page in JSP using AJAX. How can I create AJAX to send this form, from index.jsp to send.jsp without refresh page ? Thanks for all your answers.
This is form code and it s work, without AJAX. (index.jsp)
<form id="dom-realitka-notifikacia" action="send.jsp" method="post" >
<div class="stred">
<b class="cierna">E-mail:</b>
<input type="text" class="form-control form-rovno" id="email" name="email" placeholder="Sem napíšte e-mail">
<input type="hidden" value="domrealitka" id="tabulka" name="tabulka">
<input type="hidden" value="<%= rs.getInt("id") %>" id="id_realitka" name="id_realitka">
<button type="submit" class="btn btn-success">Odoslať</button>
</div>
</form>
And this is (send.jsp), work without AJAX and insert into MYSQL.
page contentType="text/html" pageEncoding="UTF-8"
page import="javax.mail.*"
page import="javax.mail.internet.*"
page import="javax.sql.*"
page import="javax.naming.Context"
page import="javax.naming.InitialContext"
page import="java.sql.*"
request.setCharacterEncoding("UTF-8");
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String email = request.getParameter("email");
int id_realitka = Integer.valueOf(request.getParameter("id_realitka"));
String tabulka = request.getParameter("tabulka");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("nacitala sa driver");
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/janko");
con = ds.getConnection();
System.out.println("nacitala sa databaza");
String sql = "INSERT INTO janko.notifikacia (email, id_realitka, tabulka) VALUES ( ?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, email);
ps.setInt(2, id_realitka);
ps.setString(3, tabulka);
ps.executeUpdate();
con.close();
}
catch(ClassNotFoundException e1) //ClassNotFoundException dame Class.forName a klikneme ctrl+space a e1 dopiseme hocico
{
System.out.println(e1.getMessage()); //vypis spravy e1 do konzoly
}
catch(SQLException e2) //SQLException mame z DriverManager.getConnection po kliknuti ctrl+space a e2 dopiseme hocico
{
System.out.println(e2.getMessage()); //vypis spravy e2 do konzoly
}
finally{
con = null;
rs = null;
ps = null;
}
The form can be dynamically submitted easily using jQuery. Just include jQuery in your file and paste the following code in your HTML file.
<script>
$.ajax({url: "send.jsp",
data: $('#dom-realitka-notifikacia').serialize(),
success: function(result){
//do something like showing success message
}});
</script>
This code will serialize your form data and send it to the concerned servlet. The servlet code remains the same.
I tried searching but no success i want to upload max 5 images to database along with user form data.I have table where all user data of form posted is saved along with images uploaded[image upload is attached with user form] picture fields in database are named as pic1,pic2,pic3.. pic5 + email,password etc I am successfull in uploading image data to database but not images.
//controller
if ($this->form_validation->run()!=true) {
$data['countryDrop'] = $this->Country_states_cities->getCountries();
$this->load->view('header');
$this->load->view('register',$data); //Display page
$this->load->view('footer');
}else{
$form=array();
$form['first_name']=$this->input->post("first_name",true);
$form['last_name']=$this->input->post("last_name",true);
$form['dob']=date('Y-m-d',strtotime($this->input->post("dob",true)));
$form['email']=$this->input->post("email",true);
$form['password']=sha1($this->input->post("password",true));
$form['phone']=$this->input->post("phone",true);
$form['addline2']=$this->input->post("addressline2",true);
$form['zip']=$this->input->post("zip",true);
$result = $this->Couch_reg->insert_new_user($form); //call to model
//model
function insert_new_user($form)
{
$this->db->insert('tbl_usrs',$form);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
//view
<input type="file" name="uploadfile[]" accept = "image/*" multiple = "multiple" size="20" /> <br />
as we can see model part is very short i want to collect images name in array form and send it to database.
You need to save the images in the upload folder and save the image name in the database.
<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>
Then create controller
make funtion inside it:
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
Hope this will help you.
For more you can try this: http://w3code.in/2015/09/upload-file-using-codeigniter/