I am facing an issue while downloading the file added into the database. I am using AngularJS and Spring MVC architecture.
In a table I am displaying filenames I have added.
Here is my html
fee.html
<td><a href="./filedownload/{{fee.fileName}}/feespath">
{{fee.fileName}}</a></td>
Here is Spring Controller.java
#RequestMapping(value="/filedownload/{fileName:.+}/{path}",method=
{RequestMethod.GET,RequestMethod.POST})
public void filedownload(#PathVariable String
fileName,#PathVariable String path,HttpServletResponse response)
{
Path file = Paths.get(context.getRealPath("/"+path+"/"),
fileName);
if (Files.exists(file))
{
response.setContentType("*/*");
response.addHeader("Content-Disposition", "attachment;
filename="+fileName);
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
And while adding I am using "feespath" as the path name that I am using in my html. Here is how I am creating a path by name feespath
#RequestMapping(value="/uploadFeeFiles",method=
{RequestMethod.GET,RequestMethod.POST})
public #ResponseBody String uploadFeeFiles(HttpServletRequest
request,HttpServletResponse response,MultipartHttpServletRequest
mRequest,Principal principal)
{
String status="";
try
{
mRequest = (MultipartHttpServletRequest) request;
mRequest.getParameterMap();
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext())
{
MultipartFile file = mRequest.getFile(itr.next());
String fileName =
uploadPathService.getFilesPath(file,"feespath");
status = fileName;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return status;
}
I am able to display file names correctly in the table but if I click on it it's redirecting to a blank page with url
http://localhost:8080/MyProject/filedownload/12802889_1263849593630301.jpg/feespath
So I am not able to figure it out. If anyone can introduce some ideas, I'll be very helpful.
Related
I've researched different solutions to this problem, but none of them works for me. I am trying to download a file from Firebase (which I am successful in doing) and then I am trying to open that file in my app right after the download completes. However, my app either crashes or does nothing.
Below is the code for downloading the file (from FirebaseStorage which works):
public void download(String name) {
final String pdf_name = name.substring(0, name.lastIndexOf('.'));
storageReference = firebaseStorage.getInstance().getReference();
ref=storageReference.child("Auctions/" + name);
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFile(ActiveAuctionsActivity.this, pdf_name, ".pdf", DIRECTORY_DOWNLOADS, url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
SpannableString spannableString = new SpannableString("אין תיק עבודה למכרז זה");
spannableString.setSpan(
new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light)),
0,
spannableString.length(),
0);
Toast.makeText(ActiveAuctionsActivity.this, spannableString, Toast.LENGTH_LONG).show();
}
});
}
public void downloadFile(Context context, String fileName, String fileExtention, String destinationDirectory, String url){
DownloadManager downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDescription("מוריד.....");
//request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtention);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName + fileExtention);
// call allowScanningByMediaScanner() to allow media scanner to discover your file
request.allowScanningByMediaScanner();
downloadmanager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Toast.makeText(getApplicationContext(), "מוריד את התיק העבודה.....",
Toast.LENGTH_SHORT).show();
}
After, I setup the receiver with the openFile() method:
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(getApplicationContext(), "ההורדה הסתיימה",
Toast.LENGTH_LONG).show();
openFile("GMU.pdf");
}
};
public void openFile(String fileName){
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri path = Uri.fromFile(file);
Log.i("Fragment2", String.valueOf(path));
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ActiveAuctionsActivity.this, "error", Toast.LENGTH_LONG).show();
}
}
Again, the file does download, but doesn't open.
What am I doing wrong, could you please advise me?
EDIT
I also tried the code below as my openFile() but that also doesn't work:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setDataAndType(path, pdfOpenintent.getType());
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
ActiveAuctionsActivity.this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
pdfOpenintent.setType("application/*");
startActivity(Intent.createChooser(pdfOpenintent, "No Application found to open File - " + fileName));
}
I need to insert an imagen into a SQL Server Database and i need to do it using jsp, but i don't know how to do it. Someone can teach me the best way to do that?
I wouldn't recommend use jsp alone to achieve this task as it is meant to use as a view technology.
For any file upload functionality, use #MultiPartConfig from servlet 3.0 specification.
in your jsp file:
<form method="post" enctype="multipart/form-data" action="/your-servlet-path">
<input type="file" name="myimage" />
</form>
in your servlet:
#MultiPartConfig
#WebServlet("/your-servlet-path")
public class FileUploadServlet extends HttpServlet{
#Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws Exception{
Part imagePart = req.getPart("myimage");
InputStream partInputStream = imagePart.getInputStream();
//read byte array from input stream
//insert into database (assuming that your image field is of blob type, it will accept inputStream type in JDBC API)
//and finally of course redirect to your upload result page
}
}
The above snippet is just to get you some idea on how to do file upload in servlet. It doesn't involve any file type validation or exception handling.
Here is how you can do that using the MVC pattern..I have used mysql databse in this example you can use DBMS of your preference. This code should solve your problem.
HTML CODE
add-- enctype="multipart/form-data" in your form tag in html or jsp page
model class code - encapsulate all fields
private int studentRoll;
private String studentName;
private String studentClass;
private String studentAddress;
private Object studentImage;
private byte image_data[];
servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
if (request.getParameter("submit") != null) {
String student_Name = request.getParameter("student_name");
String student_Class = request.getParameter("student_class");
String student_Address = request.getParameter("student_address");
Part student_Image = request.getPart("student_image");
StudentModel student = new StudentModel();
student.setStudentName(student_Name);
student.setStudentClass(student_Class);
student.setStudentAddress(student_Address);
student.setStudentImage(student_Image);
StudentDAO stu_dao = new StudentDAO();
stu_dao.insertStudent(student);
}
}catch(Exception ex){
ex.printStackTrace();;
}
}
Connection class - DatabaseConnection.java
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/newstudentdatabase", "root", "");
return connect;
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
}
return null;
}
}
dao class - insert method
public void insertStudent(StudentModel student) {
try (Connection connect = DatabaseConnection.getConnection()) {
String query = "insert into studentrecord(student_name, student_class, student_address, student_image) values(?,?,?,?)";
PreparedStatement message = connect.prepareStatement(query);
message.setString(1, student.getStudentName());
message.setString(2, student.getStudentClass());
message.setString(3, student.getStudentAddress());
message.setBlob(4, ((Part) student.getStudentImage()).getInputStream());
message.execute();
connect.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am creating a mobile app where I need users to be able to select multiple images. I am using the cn1 lib file chooser but I am only able to select one Image. How can I select multiple images. Here is the code I use to select the image.
chooseImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
animateImage.show();
if (FileChooser.isAvailable()){
FileChooser.showOpenDialog(".jpg,.png,.gif", e2->{
String file = (String)e2.getSource();
if (file == null){
animateImage.add("No File Was Selected");
animateImage.revalidate();
}else {
String extension = null;
if (file.lastIndexOf(".") > 0){
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("txt".equals(extension)){
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
animateImage.addComponent(new SpanLabel(Util.readToString(fis)));
} catch (Exception ex) {
Log.e(ex);
}
}else{
try{
Image image = URLImage.createImage((String)e2.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}
//animateImage.add("Selected file "+file);
}
}
animateImage.revalidate();
});
/*try{
Image image = URLImage.createImage((String)evt.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}*/
}
}
});
Thanks
There is no support for that in the cn1lib. You can fork the cn1lib and add support for it manually by changing the native code in the lib.
This isn't supported currently in the standard Codename One API, there is an RFE to add it here: https://github.com/codenameone/CodenameOne/issues/2383
Hi I'm trying to use the tokenizer in OpenNLP to develop a maven project. It needs to load a local file, but I don't know how to add it into the project so that even when I launched the project in other machine it still works. Like below, the project need to load this local file, how should I configure the file to be added into the project?
InputStream modelIn;
try {
modelIn = new FileInputStream("E:\\en-token.bin");
// Make sure the "en-token.bin" file is already in your local disk
TokenizerModel model = null;
try {
model = new TokenizerModel(modelIn);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize(string);
List<String> tokenResult = Arrays.asList(tokens);
return tokenResult;
} catch (FileNotFoundException ex) {
return null;
}
Such kind of files should be put into src/main/resources folder which will be packaged into jar file.
hi i am building a dynamic web project in which the welcome page have struts2 file tag now i want to store that specified file to mysql database would some one help me...
Thanks in advance.
Here is the Code i developed but it takes the file parameter statically means manually i am specifying path. but it should take path from the struts 2 file tag see the java class u will get it..
public class FileUploadACtion
{
public String execute() throws IOException
{
System.out.println("Hibernate save image into database");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
//save image into database
File file = new File("C:\\mavan-hibernate-image-mysql.gif");
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
FileUpload tfile = new FileUpload();
avatar.setImage(bFile);
session.save(tfile);
//Get image from database
FileUpload tfile2 = (FileUpload)session.get(FileUpload.class,FileUpload.getAvatarId());
byte[] bAvatar = avatar2.getImage();
try{
FileOutputStream fos = new FileOutputStream("C:\\test.gif");
fos.write(bAvatar);
fos.close();
}catch(Exception e){
e.printStackTrace();
}
session.getTransaction().commit();
}
}
You should be storing the image in the table as a BLOB type. Lets assume you have a Person class with the an image of the person stored in the DB. If you want to map this, just add a property in your person POJO that holds the image.
#Column(name="image")
#Blob
private Blob image;
When you display it, convert it to a byte[] and show.
private byte[] toByteArray(Blob fromImageBlob) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
return toByteArrayImpl(fromImageBlob, baos);
} catch (Exception e) {
}
return null;
}
private byte[] toByteArrayImpl(Blob fromImageBlob,
ByteArrayOutputStream baos) throws SQLException, IOException {
byte buf[] = new byte[4000];
int dataSize;
InputStream is = fromImageBlob.getBinaryStream();
try {
while((dataSize = is.read(buf)) != -1) {
baos.write(buf, 0, dataSize);
}
} finally {
if(is != null) {
is.close();
}
}
return baos.toByteArray();
}
You can see the below examples to know more about it.
http://i-proving.com/space/Technologies/Hibernate/Blobs+and+Hibernate
http://snehaprashant.blogspot.com/2008/08/how-to-store-and-retrieve-blob-object.html
http://viralpatel.net/blogs/2011/01/tutorial-save-get-blob-object-spring-3-mvc-hibernate.html
Well you need not to do this manually and when you will use Struts2 to upload the file, its build in file up-loader interceptor will do the major uplifting for you.
All you need to specify some properties in your action class so that Framework will inject the require data in your action class and you can do the other work.
here is what you have to do.In you JSP page you need to use <s:file> tag
<s:form action="doUpload" method="post" enctype="multipart/form-data">
<s:file name="upload" label="File"/>
<s:submit/>
</s:form>
The fileUpload interceptor will use setter injection to insert the uploaded file and related data into your Action class. For a form field named upload you would provide the three setter methods shown in the following example:
And in you action class this is all you have to do
public class UploadAction extends ActionSupport {
private File file;
private String contentType;
private String filename;
public void setUpload(File file) {
this.file = file;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
public String execute() {
//...
return SUCCESS;
}
}
The uploaded file will be treat as a temporary file, with a long random file name and you have to copy this inside your action class execute() method.You can take help of FileUtils.
I suggest you to read the official File-upload document of Struts2 for complete configurations Struts2 File-upload