Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Upload files... 4

Status
Not open for further replies.

tarawfp

IS-IT--Management
Jul 5, 2004
17
US

I want to creat a web page that allows me to upload file and generate a dynamic link by using the file name...any hints on how to do that

Many Thanks!!
 
OK.

The whole manipulation of "saveFile" takes out all the path information and strips it down to just the filename. So id the user uploaded a file called :

"C:/Docs And Settings/Billy Smith/work/myfile.doc"

then the saveFile at this point :
Code:
FileOutputStream fileOut = new FileOutputStream(saveFile);

will be "myfile.doc".

So if you want to add your own paths in, then just add them before that line above, eg :

Code:
saveFile = "/usr/local/downloads/" +saveFile;
FileOutputStream fileOut = new FileOutputStream(saveFile);

You could have always worked out what it was doing yourself by adding some "System.out.println(saveFile);" calls after saveFile was manipulated, but there you go !



--------------------------------------------------
Free Database Connection Pooling Software
 
Im having a problem with file upload when it comes to upload binary files (doc.pdf....) on a unix operating system. does anyone have a clue on how to solve it.


Thanks
 
What streams are you using to read the and write the data ? You must use streams that are compatible with binary data - not ASCII orientated streams - ie DataInputStream and FileOutputStream - as my original example shows ...

--------------------------------------------------
Free Database Connection Pooling Software
 
yup, sedj is right. I had the same exact problem. I was using a Reader insead of a DataInputStream. The reader converts the data to characters while the InputStream classes keep the data in binary format.
 

THIS IS THE CODE IM USEING...WHICH I TOOK FROM SEDJ AND i DID SOME MODIFICATIONS AS I NEED TO READ THE YEAR TOO FROM THE JSP PAGE. IM SORTING THE FILES BY YEAR. CAN YOU PLEASE HELP ME TO FIND THE ERROR......THANKS :)
/*
* uploadservlet.java
*
* Created on October 31, 2004, 7:37 PM
*/

package PFMS.servlet;

import java.io.*;
import java.lang.reflect.Array;

import java.net.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.StringTokenizer;

import javax.servlet.*;
import javax.servlet.http.*;
import PFMS.data.FileLoad;
import PFMS.data.UserRoleDo;
import PFMS.data.UserRoleManager;
import PFMS.db.Connector;

/**
*
* @author ss000091924
* @version
*/
public class fileuploadservlet extends HttpServlet {


/** Initializes the servlet.
*/
private Connection conn;
private Connector ctr;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ctr = new Connector();

}

/** Destroys the servlet.
*/
public void destroy() {

}

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
conn = ctr.getConnection();

String fdate = request.getParameter("year");
String ftype= request.getParameter("FileType");

HttpSession session = request.getSession();
UserRoleDo user = (UserRoleDo)session.getAttribute("user");

String userid= user.getuserid();
// out.println("File Info:" + userid + "," + fdate +"," +ftype);

String contentType = request.getContentType();
System.out.println("Content type is :: " +contentType);
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
//Get File Name
String file = new String(dataBytes);
System.out.println(file);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

//get year
String yearf = new String(dataBytes);
//System.out.println(yearf);
String saveyear = yearf.substring(yearf.indexOf("name=\"year"));
System.out.println("this year ="+ saveyear);
StringTokenizer ss = new StringTokenizer(saveyear,"\n");
ss.nextToken();
ss.nextToken();
saveyear = ss.nextToken();
// System.out.println(" get the > " + saveyear);
//Get File ContextPosition

int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
System.out.println("boundary" + boundary);

int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
System.out.println("pos" + pos);

int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
ServletContext RP = getServletConfig().getServletContext();
String FilePath = RP.getRealPath("/PFMS/files");
String CompletePath = FilePath + "/" + userid + "-" + saveFile;
System.out.println(CompletePath);
//File dir = new File(FilePath);

// File dir = new File(FilePath + "/" + userid);
// if(!dir.exists()) dir.mkdir();

File uploadfile = new File(CompletePath);

if(!uploadfile.exists())
uploadfile.createNewFile();



FileOutputStream fileOut = new FileOutputStream(uploadfile);
String context = file.substring(startPos,endPos);
//fileOut.write(dataBytes);
//fileOut.write(dataBytes, startPos, (endPos - startPos));
// byte[] context = new byte[(endPos - startPos)];
// for(int i = 0; i < context.length; i++) {
// context = dataBytes[(i+startPos)];
// }

fileOut.write(context.getBytes());
fileOut.flush();
fileOut.close();

saveFile = userid + "-" + saveFile;
out.println("File saved as " +saveFile);
// out.println("File Info:" + userid+ "," +
// saveFile + "," +
// fdate +"," +ftype);
FileLoad filel = new FileLoad(userid,saveFile,saveyear,CompletePath);
UserRoleManager urm = new UserRoleManager();

try{
int total =urm.InsertF(conn,filel);
}
catch(SQLException sqlE) {
sqlE.printStackTrace();
request.setAttribute("errMsg",sqlE.getMessage());
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/PFMS/errormsg.jsp");
dispatcher.forward(request,response);
return;
}
}


out.close();
}

/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}

}
 
Can anyone help me modify my code.. it still give me the out of boundary error when I upload to a unix server

Thanks
 
Hi,

When the request is of type mulitpart then you can use request.getParameter(String) it will return null.

My suggition would be use either jakarta-commons fileupload or orelly mulitpart in your classpath then you donot have to reinvent the wheel.

Cheers
Venu
 
venur : There is no need to use a 3rd party API to do it - that code works in my company every day with no problem :)

--------------------------------------------------
Free Database Connection Pooling Software
 
the code does indeed work flawlesly.
My problem was that when uploading large files, the processing time was significant. I implemented the FileUpload package from Apache Commons and it really did cut down on the time. Also, its very easy to use, all you need too do is call a couple of methods and youre done - quite simple to implement.

cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top