Exactly which file extension can be uploaded through Apache Commons FileUpload - java

I am using Apache Commons FileUpload for uploading the file .
I am not able to upload xml,js,css files on the server but its working fine for pdf,txt,jsp.It shows the file with ".tmp" extension.Can anyone tell me which file extensions are supported by "Apache Commons FileUpload" ?
I was even able to upload zipped txt/pdf files but when i tried the same for xms/js/css files, it didn't work.
public class FileLocationContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists()) file.mkdirs();
System.out.println("File Directory created to be used for storing files>>>>>"+rootPath +"##"+ File.separator + relativePath);
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}
----------------------------------CONTROLLER--------------------------------------
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
#Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
System.out.println("INSIDE INIT--");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
System.out.println("INSIDE GET METHOD :----"+fileName);
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(getServletContext().getAttribute("FILES_DIR")+File.separator+(fileName).substring(3));
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null? mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024];
int read=0;
while((read = fis.read(bufferData))!= -1){
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
System.out.println("****"+getServletContext().getAttribute("FILES_DIR"));
File file = new File(getServletContext().getAttribute("FILES_DIR")+File.separator+(fileItem.getName()).substring(3));
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileItem.getName()+"");
}
} catch (FileUploadException e) {
out.write("Exception in uploading file1.");
} catch (Exception e) {
out.write("Exception in uploading file.");
}
out.write("</body></html>");
}
}

Related

Excel file corrupted when downloaded via servlet

I have the following servlet that downloads a xlsx file, however the file is corrupted when downloaded. The original file is 12.8 KB, but the downloaded one is 20.8 KB
Below is my code
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String fileName = "MyFile.xlsx";
URL url = getClass().getResource("/" + fileName);
File f = new File(url.getPath());
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
final int size = 1024;
try {
response.setContentLength(fin.available());
final byte[] buffer = new byte[size];
ServletOutputStream os = null;
os = response.getOutputStream();
int length = 0;
while ((length = fin.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
fin.close();
os.flush();
os.close();
} catch (final IOException e) {
e.printStackTrace();
}
}catch (final Exception ex){
}
}
}
Any idea why this happening?

Download a file from JSP

I'm trying to download a file from JSP, but to no avail.
I created a button that calls a method in my controller
#RequestMapping(value = "scaricaFile", method = RequestMethod.POST)
public void getScaricaFile(HttpServletRequest request, HttpServletResponse response) {
String nome_file = request.getParameter("nome_file");
UploadAndDownload downloadFile = new UploadAndDownload();
downloadFile.download(nome_file, response);
}
the download function is
public void download(String allegato, HttpServletResponse response){
try {
File file = new File(path + allegato);
response.setContentType("application/download");
response.addHeader("Content-Disposition", "attachment; filename=" + file.getName());
response.setContentLength((int) file.length());
FileInputStream input = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(input);
FileCopyUtils.copy(buf, response.getOutputStream());
} catch (IOException e) {
System.out.println("Errore nel download del file!");
e.printStackTrace();
}
}
But on my chrome page the download does not open. Why?

automatically unzip file while downloading that zip file

I have a download button in my webpage where when i click it, it downloads a zip file. now i want to have a function like, when i click the download button the zip file should automatically extract and save in a user defined folder.
i have an idea that if we can create a exe file and add it to the download button then it should automatically extract the zip file and save in folder
%>
<td align="center">
<img onclick="pullReport('<%=reportPath.toString()%>');" title="Click to download this Report" src="./images/down-bt.gif"/>
</td>
</tr>
<%} %>
this is the method that creates zip file
public ActionForward pullReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws SQLException{
Connection connection=null;
boolean cont=false;
failureList.clear();
logger.info("dispatch = pullReport");
String filePaths=null;
String filePath = null;
String fileName = null;
String srcFileName = null;
String directory = null;
try{
Properties props = Application.getProperties();
String basePath = props.getProperty("std.report_location");
logger.info(" basepath " + basePath);
connection=ConnectionManager.getConnection();
StandardReportsForm standardReportsForm=(StandardReportsForm)form;
filePaths=standardReportsForm.getFilePath();
logger.info("filepaths " + filePaths);
ServletOutputStream fos = null;
InputStream is = null;
String [] filePathArr = filePaths.split(",");
FileIO fio = null;
FileIO srcFio = null;
if (filePathArr.length > 1) {
filePath = filePathArr[0].substring(0,filePathArr[0].lastIndexOf("."))+".zip";
logger.info(filePath + " creating zip file ......");
directory = basePath+filePath.substring(0,filePath.lastIndexOf('/'));
logger.info( " Direcory Name :" +directory);
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
logger.info( " File Name :" +fileName);
fio = new FileIO(directory,fileName);
fio.mkDir();
byte[] buffer = new byte[1024];
OutputStream fosForZip = fio.createOutputStream();
ZipOutputStream zos = new ZipOutputStream(fosForZip);
InputStream fis = null;
for (int i=0; i < filePathArr.length; i++) {
srcFileName = filePathArr[i].substring(filePathArr[i].lastIndexOf('/')+1);
srcFio = new FileIO(directory,srcFileName);
if (srcFio.isFileExist()) {
cont=true;
logger.info(" adding into zip file " +srcFileName);
fis = srcFio.createInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(srcFileName));
int length;
while ((length = bis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
bis.close();
srcFio.closeInputStream(fis);
} else {
logger.info(srcFileName + " file does not exist on shared drive");
cont =false;
break;
}
}
FileIO.closeOutputStream(zos);
if (!cont){
standardReportsForm.setMissingFileName(srcFileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
} else {
filePath = filePathArr[0];
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
}
if (basePath.startsWith("smb")) {
SmbFile smbFile = new SmbFile(basePath+filePath,SMBHelper.getInstance().createAuthFromSmbLocation(basePath));
if(smbFile.exists())
{
is = new SmbFileInputStream(smbFile);
cont=true;
}
} else {
File file=new File(basePath+filePath);
if(file.exists())
{
is = new FileInputStream(file);
cont=true;
}
}
if(cont)
{
fos=response.getOutputStream();
setContentType(response, fileName);
//fos.write (baos.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = is.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
byte[] bytes = bos.toByteArray();
fos.write(bytes);
fos.flush();
fos.close();
} else {
standardReportsForm.setMissingFileName(fileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
}catch(SQLException sx) {
logger.error(" error log SQLException " ,sx);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_CONN_EXEC"), sx));
} catch(NamingException ne) {
logger.info("RMI error is "+ne);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_NAMING_EXEC"), ne));
} catch(Exception e) {
logger.error(" error log Exception " ,e);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_GEN_EXEC", new String[] {"General Exception"}), e));
} finally {
SQLHelper.closeConnection(connection, failureList, logger);
}
return null;
}
yah you can use java code to unzip the file.here is the example
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipUtility {
public String zipFilePath= "D:/javatut/corejava/src/zipfile.zip";
public String destDir = "D:/javatut/corejava";
private static final int BUFFER_SIZE = 4096;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
UnzipUtility uu = new UnzipUtility();
uu.unzip(uu.zipFilePath, uu.destDir);
}
public void unzip(String zipFilePath,String destDir)throws IOException{
File destDirectory = new File(destDir);
if(!destDirectory.exists()){
destDirectory.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry zipEntry = zipIn.getNextEntry();
while(zipEntry!=null){
String filePath=destDir+File.separator+zipEntry.getName();
if(!zipEntry.isDirectory()){
extractFile(zipIn,filePath);
}
else{
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
zipEntry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws FileNotFoundException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
try {
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
thank you.......
please follow this path and (clear) automatic files viewer
chrome://settings/onStartup/Advanced/Downloads/automatic file viewer (clear)

export content to a text file using java with save dialog

i have a result set which has got some values, i want to export the data which is there in result set as a text file with the save dialog.
how to do this in java?.
I have done the above requirement for excel and java like the following.
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".xls\"");
and
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
UPDATE :
if(exportTo.equals("text")){
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".txt\"");
try {
} catch (Exception e) {
// TODO: handle exception
}
}
in this
in try block how to set the contents which are avilable from resultset to a output stream and make it available.
the only difference is this :
response.setContentType("text/plain");
You can see a full example here ( http://www.mkyong.com/servlet/servlet-code-to-download-text-file-from-website-java/ )
UPDATE
This is a demo that I have developed and tested and works perfectly fine:
public class ServletDownloadDemo extends HttpServlet {
private static final int BYTES_DOWNLOAD = 1024;
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
String s = "Test\n\nText file contects!!";
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while ((read = input.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
It downloads a text file named downloadname.txt with the contents of String s.
UPDATE 2
String s = "";
while (rs.next()) {
s += rs.getString("column_name");
}
if (exportTo.equals("text")) {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
try {
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
//data form resultset
while ((read = input.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
} catch (Exception e) {
// TODO: handle exception
}
}
You have to populate your ResultSet and place what you need in String s. That's all.

Downloaded File Size 0

I'm trying here to add a specific dialog bean for action on Alfresco Explorer that supposed to download a specific docx file. The code is working fine when I hit the download action, it downloads the file but as mentioned in my question title, the file size is 0 bytes.
I'm using this to do that:
public class NewFormDialog extends BaseDialogBean {
protected String aspect;
protected String finishImpl(FacesContext context, String outcome)
throws Exception {
download(aspect);
// // get the space the action will apply to
// NodeRef nodeRef = this.browseBean.getActionSpace().getNodeRef();
//
// // resolve the fully qualified aspect name
// QName aspectToAdd = Repository.resolveToQName(this.aspect);
//
// // add the aspect to the space
// getNodeService().addAspect(nodeRef, aspectToAdd, null);
//
// // return the default outcome
return outcome;
}
public boolean getFinishButtonDisabled() {
return false;
}
public String getFinishButtonLabel() {
return "Download";
}
public void download(String pAspect) throws ServletException, IOException {
String filename = pAspect;
String filepath = "\\";
BufferedInputStream buf = null;
ServletOutputStream myOut = null;
try {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc
.getExternalContext().getResponse();
myOut = response.getOutputStream();
File myfile = new File(filepath + filename);
// set response headers
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename="
+ filename);
response.setContentLength((int) myfile.length());
FileInputStream input = new FileInputStream(myfile);
buf = new BufferedInputStream(input);
int readBytes = 0;
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
myOut.write(readBytes);
myOut.flush();
response.flushBuffer();
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
// close the input/output streams
if (myOut != null)
myOut.close();
if (buf != null)
buf.close();
FacesContext.getCurrentInstance().responseComplete();
}
}
public String getAspect() {
return aspect;
}
public void setAspect(String aspect) {
this.aspect = aspect;
}
}
I tried every solution that I found by none works.
Thank you in advance.
The File.length() method returns 0 if the file does not exist. Check to make sure that the file exists.
Tip: The Apache Commons IO library simplifies many I/O related tasks. For example, the following code snippet streams the contents of a file to the servlet response:
HttpServletResponse response = ...
File myfile = ...
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(myfile);
out = response.getOutputStream();
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in); //checks for null
IOUtils.closeQuietly(out); //checks for null
}

Categories