Uploading a file in struts1 - java

I want to upload a file in struts1 application.
Currently the implementation is using File, like this:
<html:file property="upload"/>
But this does not allow to upload file if app is accessed from remote machine as this widget passes only the name of the file instead the whole file.

using only <html:file property="upload" /> will not make your application to upload a file.
to support upload functionality,your form must have enctype="multipart/form-data"
<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
File : <html:file property="upload" />
<br/`>
<html:submit />
</html:form`>
and in action get file from your form bean and manipulate it as follows
YourForm uploadForm = (YourForm) form;
FileOutputStream outputStream = null;
FormFile file = null;
try {
file = uploadForm.getFile();
String path = getServlet().getServletContext().getRealPath("")+"/"+file.getFileName();
outputStream = new FileOutputStream(new File(path));
outputStream.write(file.getFileData());
}
finally {
if (outputStream != null) {
outputStream.close();
}
}

Related

Java Web project Integration with Dropbox API

I am facing trouble in integrating my project with dropbox I use Dropbox For
upload file here I am able to upload the file by giving complete Path Of file. but I want to upload file by selecting or Brows from the system and upload to my dropbox Here my code is Like Static For Uploading the file by giving complete file path for upload now I want to upload file by selecting from disck here I use this code for selecting the file but i dont know how to pass this selected file as input for FileInputStream in my DbxUpload class
<body>
<a>Select to Upload</a><br><br>
Select file: <br />
<form action="DbxUpload" method="Post" enctype="multipart/form-data">
<input type="file" name="file" size="70" />
<br />
<input type="submit" value="Upload File" />
Here my DbxUpload Class code that iam using
import com.dropbox.core.*;
import java.io.*;
public class DbxUpload
{
private static final String ACCESS_TOKEN = "XXXXXXXXXXXXXXX";
public static void main(String args[]) throws DbxException, IOException {
// Create Dropbox client
DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial", "en_US");
DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
// Get current account info
FullAccount account = client.users().getCurrentAccount();
System.out.println(account.getName().getDisplayName());
// Get files and folder metadata from Dropbox root directory
ListFolderResult result = client.files().listFolder("");
while (true) {
for (Metadata metadata : result.getEntries()) {
System.out.println(metadata.getPathLower());
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
}
// Upload "test.txt" to Dropbox
try (InputStream in = new FileInputStream("D:/RUNNING.txt")) {
FileMetadata metadata = client.files().uploadBuilder("/RUNNING.txt")
.uploadAndFinish(in);
}
}
}
Please Help me Thanks in Advance
Using web File browser, this is the entry point https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/web-file-browser/src/main/java/com/dropbox/core/examples/web_file_browser/Main.java where the user can start browse and upload a file to drop box api using Jetty application (uses Jetty server and servlet in the program to support file upload to drop box)
Ref :
https://github.com/dropbox/dropbox-sdk-java/tree/master/examples/web-file-browser/src/main/java/com/dropbox/core/examples/web_file_browser

Primefaces Download File Which is Outside FacesContext

I'm uploading an Excel Workbook to a directory which is outside the application context (for backup purposes) and saving its path into the database.
Now I need to download that file and I'm trying to use Primefaces Download, but I'm getting a null file.
Here is my code (much like Primefaces Showcase Download section):
Bean:
private StreamedContent file;
public void download(Arquivo arquivo) throws IOException {
InputStream stream = ((ServletContext)FacesContext.getCurrentInstance()
.getExternalContext().getContext()).getResourceAsStream(arquivo.getNomeArquivo());
file = new DefaultStreamedContent(stream);
}
View:
<h:commandLink id="btnDownload" title="Download Arquivo"
actionListener="#{arquivoBean.download(obj)}">
<p:fileDownload value="#{arquivoBean.file}" />
</h:commandLink>
Basically I need to pass an external path to InputStream instead of FacesContext.
From what I see my problem is that I'm passing my application context to the InputStream, appending the path in the argument of getResourceAsStream which, of course, is not found.
I'm new to this FileDownload thing. Thanks in advance!
If it can still be useful :
StreamedContent streamToReturn = DefaultStreamedContent.builder().name(FILE_NAME).contentType( FacesContext.getCurrentInstance().getExternalContext()
.getMimeType(FILE_PATH))
.stream(() -> {
try {
return new FileInputStream(FILE_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}).build();

Uploading a file in Java Servlet

I have a Java Dynamic Web Project, and I'm using TomCat v7.0.
I am new to web projects and I didn't quite understand how I can upload a file in one of my jsp pages. Since my project is intended to be only local, I thought I could use a multipart form in which the person would choose the file (and this part goes fine) and later retreive the file path from my Servlet. I can't complete this part though, it appears to only give me the name of the file, not its entire path.
Can anyone point me to the right direction? I've read several posts about Apache File Upload and retreiving information from the multipart form but nothing seems to help me.
How can I get the file path from a form or alternatively how can I get the uploaded file to use in my Java classes?
Thanks in advance.
.jsp:
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="filePath" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"></input>
<input type="submit" value="Enviar"></input>
</form>
Java Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html><body>");
try
{
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items)
{
if (item.isFormField())
{
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
out.println("<h1>"+fieldname+" / "+fieldvalue+"</h1>");
}
else
{
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = item.getName();
InputStream filecontent = item.getInputStream();
String s = filecontent.toString();
out.println("<h1>"+s+" / "+filename+"</h1>");
item.write(null);
}
}
}
catch (FileUploadException e)
{
throw new ServletException("Cannot parse multipart request.", e);
}
catch (Exception e)
{
e.printStackTrace();
}
out.println("</body></html>");
}
Not providing the file path is a security feature of the browser.
You have the file contents available in your code (InputStream filecontent) so you could use that or use one of the convenience methods on FileItem, e.g.
item.write(new File("/path/to/myfile.txt"));

Rendering generated png into JSF

I built an image form PDF doc inside a JSF backing bean, i need to show image inside JSF page. I found that primefaces has a component named , I defined a variable:
private StreamedContent pdfImage;
according to this example http://www.primefaces.org/showcase/ui/dynamicImage.jsf. In my code
i built pdf using some data and apache PDFBox and save document into:
private byte[] bytesPdf;
My jsf line is
<p:graphicImage value="#{myBean.pdfImage}" rendered="#{myBean.showImage}"/>
After that i call following method that tranform first PDF document page to PNG i get:
public void buildPDFImage() throws IOException{
ByteArrayOutputStream os = new ByteArrayOutputStream();
//Build bufferedImage from pdf bytearray
InputStream input = new ByteArrayInputStream(bytesPdf);
PDDocument archivo=new PDDocument();
archivo=PDDocument.load(input);
PDPage firstPage = (PDPage) archivo.getDocumentCatalog().getAllPages().get(0);
BufferedImage bufferedImage = firstPage.convertToImage();
//File exit=new File("d:/exit.png"); if i do something like this and pass file as param to iowrite image is generated on file system
try {
ImageIO.write(bufferedImage, "png", os);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pdfImage = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
}
When i run my app after generate pdf image i get this trace
GRAVE: Error Rendering View[/pages/apphuella.xhtml]
java.lang.IllegalStateException: PWC3999: Cannot create a session after the response has been committed
at org.apache.catalina.connector.Request.doGetSession(Request.java:2880)
at org.apache.catalina.connector.Request.getSession(Request.java:2577)
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:920)
at com.sun.faces.context.SessionMap.getSession(SessionMap.java:235)
at com.sun.faces.context.SessionMap.put(SessionMap.java:126)
at com.sun.faces.context.SessionMap.put(SessionMap.java:61)
at org.primefaces.component.graphicimage.GraphicImageRenderer.getImageSrc(GraphicImageRenderer.java:105)
at org.primefaces.component.graphicimage.GraphicImageRenderer.encodeEnd(GraphicImageRenderer.java:45)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at
I would know if i´m using correctly if don´t how could i use it to show generated png(and other images)?, also if there´s other option to show runtime generated images on JSF pages.
Thanks in advance
At first, you need to keep the file a temporary directory. After that you should render the file again.
Try as below
Backing Bean
private String filePath;
public String filePath() {
return filePath;
}
private String getSystemPath() {
Object context = getFacesContext().getExternalContext().getContext();
String systemPath = ((ServletContext)context).getRealPath("/");
return systemPath;
}
public void buildPDFImage() throws IOException {
// create any kind of file types.
byte[] cotent = --> take byte array content of your files.
Stirng fileName = "xxx.pdf" or "xxx.png" --> your file name
String dirPath = "/pdf/" or "/images/"; --> a directory to place created files.
filePath = dirPath + fileName
createFile(new File(getSystemPath() + filePath), content);
}
private void createFile(File file, byte[] content) {
try {
/*At First : Create directory of target file*/
String filePath = file.getPath();
int lastIndex = filePath.lastIndexOf("\\") + 1;
FileUtils.forceMkdir(new File(filePath.substring(0, lastIndex)));
/*Create target file*/
FileOutputStream outputStream = new FileOutputStream(file);
IOUtils.write(content, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pages
<h:form enctype="multipart/form-data">
<h:commandButton value="Create"/>
<!-- Your Files is image -->
<p:graphicImage value="#{myBean.filePath}"/>
<!--
Your Files is pdf. You need PDF Viewer plugin for your browser.
My FireFox vesion is 20.0. It have default PDF Viewer.
If PDF File cannot display on your browser, it is depond on browser setting also.
-->
<p:media value="#{myBean.filePath}" width="100%" height="300px"/>
</h:form>

file upload with spring MVC

I am uploading file using spring MVC and jquery. Inside my class method I have written
#RequestMapping(value="attachFile", method=RequestMethod.POST)
public #ResponseBody List<FileAttachment> upload(
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpSession session) {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
//Save the file to a temporary location
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
fileName = realContextPath +"/images/"+file.getOriginalFilename();
//File dest = new File(fileName);
try {
//file.transferTo(dest);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fileName);
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its uploading the file correctly I am using
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
to get the path. My first question is , Is this the correct way to get the path and it stores the file somewhere at
workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images
and when I am trying to display this image on my jsp page using the following code
<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />
It does not display the image, Its generating the following html
<img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">
Am I doing the things right? In my project I have to upload large number of files everyday.
Please let me know if you need anything else to understand my question
It will be better if you upload your files in some directory by absolute path(e.g. C:\images\) instead of relative (your approach). Usually, web apps runs on linux mathines on production and it is good practice to make save path configurable.
Create some application property which will holds save path for files(in xml or property file).

Categories