Click here to Skip to main content
14,427,367 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi,
I want to save excel data to mysql database table at front-end using ajax ,jquery.

What I have tried:

i have tried this code:
$(document).ready(function(){
$('#name').change(function(){
$('#name').submit();
});
$('#name').on('submit', function(event){
// alert('HIIIII1111');
event.preventDefault();
$.ajax({
url:"readExcel",
// alert(url);
method:"GET",
data:new FormData(this),
// alert(data);
contentType:false,
processData:true,
success:function(data){
$('#demo').html(data);
$('#name').val('');
//alert('HIIIII');
}
});
});
});



<div>
<form action="${pageContext.request.contextPath}/uploadToDB" enctype="multipart/form-data" method="post">
<ol>
Select file to upload:
<br />
<input type="file" name="file" id="name" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
<br />
<br />
Description:
<br />
<input type="text" name="description" size="100" />
<br />
<br />
<input type="submit" value="Upload" />
<br/>
<br/>
<p id="demo"></p>

<table id="grid1"></table>
</ol>

</form>
</div>
Posted
Updated 3-Jan-20 17:03pm
Comments
Richard MacCutchan 3-Jan-20 7:25am
   
And what happens.
Member 14639038 3-Jan-20 7:49am
   
file uploaded but not excel data is not saved in the database
ZurdoDev 3-Jan-20 12:36pm
   
You do not show any code for saving it to the database so what do you want us to do?

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

The front end CANNOT save data to the back end. It can simply send the data to the back end, where back end code can save it. You can't attach data in a GET, unless it goes on the URL. You need a POST or PUT to have a body.
   
Comments
Member 14639038 6-Jan-20 0:12am
   
code of uploadDB servlet.
package com.mvc.upload;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.mvc.util.DBConnection;

@WebServlet("/uploadToDB")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class UploadToDBServlet extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
RequestDispatcher dispatcher = req.getServletContext().getRequestDispatcher("/WebContent/uploading_client.jsp");

dispatcher.forward(req, resp);

// try {
// readExcel.read_SaveToDB();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// String message = "data uploaded and saved into database";
// req.setAttribute("Message", message);
//
//RequestDispatcher dispatchData_toDB = req.getServletContext().getRequestDispatcher("/WebContent/DataUploaded.jsp");
//req.setAttribute("Message", message);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = null;
try {
// Connection to Database
// (See more in JDBC Tutorial).
conn = DBConnection.createConnection();
conn.setAutoCommit(false);

String description = request.getParameter("description");

// Part list (multi files).
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
if (fileName != null && fileName.length() > 0) {
// File data
InputStream is = part.getInputStream();
// Write to file
this.writeToDB(conn, fileName, is, description);
}
}
conn.commit();

// Upload successfully!.
response.sendRedirect(request.getContextPath() + "/uploadToDBResults");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorMessage", "Error: " + e.getMessage());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WebContent/uploading_client.jsp");
dispatcher.forward(request, response);
} finally {
this.closeQuietly(conn);
}
}

private String extractFileName(Part part) {
// form-data; name="file"; filename="C:\file1.zip"
// form-data; name="file"; filename="C:\Note\file2.zip"
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
// C:\file1.zip
// C:\Note\file2.zip
String clientFileName = s.substring(s.indexOf("=") + 2, s.length() - 1);
clientFileName = clientFileName.replace("\\", "/");
int i = clientFileName.lastIndexOf('/');
// file1.zip
Member 14639038 6-Jan-20 0:14am
   
but they are not executing .
neither file is not uploaded nor data is saved.
2nd point is i have used hibernate in readExcel method whereas jdbc in the uploadDB servlet
Christian Graus 6-Jan-20 0:15am
   
So use Postman to simulate your back end call and debug it. Then make sure your code makes the right call
Member 14639038 6-Jan-20 0:17am
   
can conflict of jdbc and hibernate is the cause of failure of the both of servlet
Christian Graus 6-Jan-20 0:25am
   
I have no clue. Use Postman to call your api and step through it
Member 14639038 6-Jan-20 0:50am
   
k !thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100