How are you?
Within a project that I am doing I need to obtain an image of the computer and save it in a database, for this I used the field input type = file.
To save it I use the following function:
public boolean guardarfoto(int idProducto, String imagen) {
FileInputStream fis = null;
try {
File file = new File("C:\\" + imagen);
fis = new FileInputStream(file);
cpsql.conectar();
connection = ConexionPgSQL.getCn();
PreparedStatement pstm = connection.prepareStatement("UPDATE productos SET imagen_producto = ?, nombre_imagen = ? where id_producto = ?");
pstm.setBinaryStream(1, fis, (int) file.length());
pstm.setString(2, imagen);
pstm.setInt(3, idProducto);
pstm.execute();
System.out.println("Agregando imagen: " + pstm.toString());
pstm.close();
return true;
} catch (FileNotFoundException | SQLException e) {
Logger.getLogger(ControladorProducto.class.getName()).
log(Level.SEVERE, null, e);
}
return false;
}
My problem is that this function only allows me to save an image that is inside the specified directory, in this case C: \, because if in the function I replaced the File file = new File ("C: \\" + image); by File file = new File (image); it seems to try to look for the route internally in the project, and not in the directory of the computer, and would therefore like to replace that static directory with a dynamic one so as not to limit the client to having to move the image to the specified route so that Do not mark error when saving.
For this, I am working on a Web project using NetBeans 8.0.2, JSPs and Servlets.
Related
So I tried to get data from my [database] table then generate a PDF from it. First, I tried to select the directory where I want to save the file with JFileChooser. Then, I tried to create the PDF inside the selected directories. Last, I tried to get all the data from my DB and insert it to my PDF.
The problem is that the PDF file is not generated and there is no error message showing.
String path = "";
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int x = j.showSaveDialog(this);
if(x == JFileChooser.APPROVE_OPTION){
path = j.getSelectedFile().getPath();
}
try{
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream(path + "abcd123.pdf"));
doc.open();
PdfPTable tbl = new PdfPTable(2);
tbl.addCell("Class ID");
tbl.addCell("Class Name");
try{
String query = "SELECT * FROM kelas";
PreparedStatement st = (PreparedStatement)conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()) {
tbl.addCell(rs.getString("id"));
tbl.addCell(rs.getString("nama"));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
doc.add(tbl);
doc.close();
} catch (Exception e) {
System.err.println(e);
}
So I tried to change the path from
PdfWriter.getInstance(doc, new FileOutputStream(path + "abcd123.pdf"))
to
PdfWriter.getInstance(doc, new FileOutputStream("C:\\Users\\Daniel\\Desktop\\tes.pdf"));
And it works. But I want the path to be dynamic and not hard coded.
So from your last edit of your question I will suggest to try
PdfWriter.getInstance(doc, new FileOutputStream(path + "\\abcd123.pdf"));
Also you can try to print the path to see what is the value of it.
By the way you should use file separator that works on Windows and Unix(Linux):
String fileSeparator = FileSystems.getDefault().getSeparator();
Good day everyone! I am trying to create a desktop application using java swing wherein the user can upload pdf files to the mysql database. I already did the upload part in the application, but I'm having trouble on making a download button in the application. The function of the download button is to retrieve the pdf file in the mysql database and then download it in the user's computer.
here's what I found in inserting pdf file from https://www.java-tips.org/other-api-tips-100035/69-jdbc/845-how-to-storeretrieve-pdf-document-tofrom-sqlserver.html
The above link has already a function in getting pdf data, but I can't seem to understand how to implement it in my download button.
public void upload(Connection conn,String filename) {
int len;
String query;
PreparedStatement pstmt;
try {
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
len = (int)file.length();
query = ("insert into fileStorage VALUES(?,?,?)");
pstmt = conn.prepareStatement(query);
pstmt.setString(1,file.getName());
pstmt.setInt(2, len);
//method to insert a stream of bytes
pstmt.setBinaryStream(3, fis, len);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
What I'm having a trouble is making a function for my download button. how do I retrieve the file from database and download it at the same time after clicking the download button.
Yeah so unfortunately I don't know your table format however we should be able to create a prepared statement that gets the file raw bytes from the database. The following will get the byte array from the database and then create a new file, if necessary, from the raw bytes.
Change fileName to the proper name of the column for the file name.
Change fileContent to the name of the column for the byte array.
Make sure fileContent is a varbinary type.
Replace null in my reference to download(Connection, String) with a legitimate non-null Connection reference.
public static void main(String[] args) {
try {
byte[] download = download(null, "test");
Path output = Paths.get("my", "output", "file.pdf");
Files.write(output, download, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
} catch (IOException | SQLException e) {
throw new RuntimeException("Uh oh something went wrong!", e);
}
}
static byte[] download(Connection connection, String fileName) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM fileStore WHERE fileName = ?")) {
statement.setString(1, fileName);
try (ResultSet results = statement.getResultSet()) {
if (results.next()) {
return results.getBytes("fileContent");
}
}
}
throw new IllegalStateException("No file can be found for this name.");
}
I'm trying to store documents(doc,ppt,pdf,txt..etc) in MSSQL(server running in AWS). I'm working on the app module (android). I can get the files from the user but I'm not able to upload it to the database.
What I've done so far:
Tried to upload the file directly using setBinaryStream
Tried to upload the fileInputStream using setBinaryStream
No blob type can be declared in this database column
Update
Code Requested:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sm_attachments:
FilePickerDialog filePickerDialog = new FilePickerDialog(SendMailToCustomers.this,properties);
filePickerDialog.setTitle("Select Files");
filePickerDialog.show();
filePickerDialog.setDialogSelectionListener(new DialogSelectionListener() {
#Override
public void onSelectedFilePaths(String[] files) {
for (String file : files) {
Uri uri = Uri.fromFile(new File(file));
try {
File file1 = new File(uri.getPath());
//InputStream inputStream = new FileInputStream(new File(uri.getPath()));
byte[] bytesArray = null;
bytesArray = new byte[(int) file1.length()];
FileInputStream fileInputStream = new FileInputStream(file1);
fileInputStream.read(bytesArray);
String sql = "INSERT INTO Storedata (FileName,MyFile) values (?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1,"myNewFile");
//statement.setBinaryStream(2, /*inputStream*/fileInputStream,fileInputStream.available());
statement.setBytes(2, /*inputStream*/bytesArray);
int row = statement.executeUpdate();
if(row>0){
Toast.makeText(SendMailToCustomers.this, "The File was inserted Successfully", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onSelectedFilePaths: Inserted File Successfully");
}
else{
Toast.makeText(SendMailToCustomers.this, "Failed To Insert File", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onSelectedFilePaths: Failed To Insert File");
}
} catch (Exception e) {
Log.d(TAG, "onSelectedFilePaths: "+"Exception - "+e.getMessage()+"\n");
e.printStackTrace();
}
break;
The String[] files - are the selected files(Uri) for upload.
Next is the picture of my SQL Database:
MyFile is varbinary(MAX)
Upon doing this : statement.setBytes(2, /inputStream/bytesArray);
I get the below result. But this is around 433984 byte length i.e. bytes read for one file. How should i go about this?
The BULK IMPORT would not natively be able to do this however if you are on SQL2005 or greater you can use SSIS. The first step would be to perform an Exectute Process Task and use a zip utility to unzip the file. The second step is to use the SSIS Bulk Insert task to push the data into SQL Server.
I never worked with postscript before... And I need to replace a tool that:
Converts a string to postscript
Generates a pdf file based on a postscript file (done)
My issue is: I have no idea how to achieve step 1. By the way, I would preferably do in a similar way to the one I did on step (2).
I was wondering if I can just replace the parameters, but how? Could you please assist me?
The code to item (2) is below:
public byte[] convertPostScriptToPDF() throws IOException {
//get Ghostscript instance
Ghostscript gs = Ghostscript.getInstance();
File file= new File (this.getClass().getResource( "/resources/employer_report_last_page2.ps").getFile());//(Config.EMP_REPORT.REPORT_LAST_PAGE_STORE_PATH);
File pdfGenerated = File.createTempFile("output", "pdf");
System.out.println("Path for temp file -> " + pdfGenerated.getAbsolutePath());
//prepare Ghostscript interpreter parameters
//refer to Ghostscript documentation for parameter usage
String[] gsArgs = new String[10];
gsArgs[0] = "-ps2pdf";
gsArgs[1] = "-dNOPAUSE";
gsArgs[2] = "-dBATCH";
gsArgs[3] = "-dSAFER";
gsArgs[4] = "-sDEVICE=pdfwrite";
// gsArgs[5] = "-sOutputFile=output2.pdf";//output file name
gsArgs[5] = "-sOutputFile=" + pdfGenerated.getAbsolutePath();
// gsArgs[5] = "-sOutputFile=" + file.getAbsolutePath();
gsArgs[6] = "-c";
gsArgs[7] = ".setpdfwrite";
gsArgs[8] = "-f";
// gsArgs[9] = "input.ps";//input file name
gsArgs[9] = file.getAbsolutePath();//input file name
//execute and exit interpreter
try {
gs.initialize(gsArgs);
gs.exit();
} catch (GhostscriptException e) {
System.out.println("ERROR: " + e.getMessage());
}
FileInputStream fis = new FileInputStream(pdfGenerated);
return IOUtils.toByteArray(fis);
}
Thank you in advance!
I got no solution, so I realized I could try a workaround...
I changed the application logic. At the end it would convert everything to pdf, so instead of :
convert string to ps
add ps content other ps
convert ps to string
I did:
onvertd string to pdf
convert ps to pdf
merged both using the PDFMergerUtility
I tried to create 3 empty files in my home directory, using this:
this.mainpath = System.getenv("HOME"+"/");
this.single = new File(mainpath + "sin.r");
this.complete = new File (mainpath + "com.r");
this.ward = new File (mainpath+"w.r");
I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?
Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.
However, I specifically wanted to create the file in my home!
Well, my code now reads:
this.mainpath = System.getenv("user.home");
this.mainpath = this.mainpath + "/";
this.single = new File(mainpath + "sin.r");
this.single.createNewFile();
System.out.println(this.single.getAbsolutePath());
this.complete = new File (mainpath + "comp.r");
this.complete.createNewFile();
this.ward = new File (mainpath+"w.r");
this.ward.createNewFile();
The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.
as for my code how I tried to write sth into those file, there it is:
FileWriter writer1 = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
try {
writer1 = new FileWriter(single);
writer2 = new FileWriter(complete);
writer3 = new FileWriter(ward);
writer1.write("x = cbind(1,2,3)");
writer2.write("x = cbind(1,2,3)");
writer3.write("x = cbind(1,2,3)");
writer1.flush();
writer2.flush();
writer3.flush();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
} finally {
try {
writer1.close();
writer2.close();
writer3.close();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
}
You need to use getProperty() instead
System.getProperty("user.home");
Also, the / should be appended after getting the directory path.
this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");
You can call the "createNewFile"-method for each of the objects you've declared to actually create them.