View Full Version : FileUploadField example
willbrady
20 Jul 2009, 11:23 AM
Does anyone have a working example of using the FileUploadField to upload a file to a servlet? I can send the path name of the file to the servlet, but what is the right way to actually upload the file?
All ideas are welcomed!
FireGlow
30 Jul 2009, 6:55 AM
hey!
having the same problem!
I wrote an Servlet, but it only delivres the name of the file!
public class ArchetypeUploadServlet extends HttpServlet {
private ArchetypeService archetypeService;
public final String TEMP_UPLOAD_FOLDER = "D:/server/temp/";
public ArchetypeUploadServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException {
}
/**
* Takes the upload request and uploads the file
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
try {
archetypeService = ArchetypeServiceImpl.getInstance();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> fileItems = upload.parseRequest(req);
Iterator it = fileItems.iterator();
File uploadedFile;
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
GregorianCalendar tempDate = new GregorianCalendar();
uploadedFile = new File(TEMP_UPLOAD_FOLDER + tempDate.getTimeInMillis() + ".adl");
item.write(uploadedFile);
User user = (User) req.getSession().getAttribute(User.USER_LOGGED_IN);
if (user == null) {
throw new AccessControlException("No user found in the session.");
}
archetypeService.importArchetype(uploadedFile, user);
out.println("success");
}
} catch (Exception e) {
out.println("failed");
}
}
}
I think you need to check if the item is a form field. if(item.isFormField())
catalin.ciobanu
25 Jul 2011, 2:48 AM
Have you get this working anyhow ? I'd be interested what was the problem and most of it, the way you solved it.
willbrady
2 Aug 2011, 5:24 PM
I haven't looked at this in years and never got what I was trying to do working
catalin.ciobanu
3 Aug 2011, 12:26 AM
Yeah I figured it out. Thanks.
rvanker
4 Nov 2011, 7:08 AM
Can you provide an example (client, servlet code and web.xml) ?
catalin.ciobanu
4 Nov 2011, 7:19 AM
well, client side:
public class UploadPopup extends Popup {
private static String UPLOAD_ACTION_URL = "";
public UploadPopup(String id) {
// insert_id = the id of the parent
// String mess = GWT.getHostPageBaseURL().substring(0,
// GWT.getHostPageBaseURL().lastIndexOf("/"));
UPLOAD_ACTION_URL = servletAddress //replace this
+ "/FileServlet/events?insert_id=" + id;
}
@Override
protected void onRender(Element target, int index) {
super.onRender(target, index);
final ContentPanel cp = new ContentPanel();
cp.setHeaderVisible(false);
final FormPanel form = new FormPanel();
// set the encoding and the method to submit the form
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// set the address of the action
form.setAction(UPLOAD_ACTION_URL);
ContentPanel holder = new ContentPanel();
holder.setHeaderVisible(false);
final FileUpload upload = new FileUpload();
upload.setName("upload");
holder.add(upload);
holder.add(new Button("Submit", new ClickListener() {
public void onClick(Widget sender) {
form.submit();
cp.hide();
}
}));
form.add(holder);
form.addFormHandler(new FormHandler() {
public void onSubmit(FormSubmitEvent event) {
if (upload.getFilename().length() == 0) {
Window.alert("Select a file to upload.");
event.setCancelled(true);
}
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
FilesTree.refresh();
}
});
cp.add(form);
cp.setPosition(-100, -100);
add(cp);
}
}
Server side (i do it on doPost method)
// if the event is an insert event
if (req.getParameter("insert_id") != null) {
String parentId = req.getParameter("insert_id");
String parentPath = null;
try {
parentPath = DBUtil.getPath(parentId) + "/";
} catch (SQLException e1) {
e1.printStackTrace();
}
// process only multipart requests
if (ServletFileUpload.isMultipartContent(req)) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(
(org.apache.commons.fileupload.FileItemFactory) factory);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
// process only file upload - discard other form item
// types
if (item.isFormField())
continue;
String fileName = item.getName();
// get only the file name not whole path
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
// create a new file
File uploadedFile = new File(parentPath, fileName);
if (uploadedFile.createNewFile()) {
item.write(uploadedFile);
resp.setStatus(HttpServletResponse.SC_CREATED);
resp.getWriter().print(
"The file was uploaded successfully.");
resp.flushBuffer();
// update the database
boolean updateDB = DBUtil.updateDB(parentId, 0,
fileName, parentPath + fileName);
if (!updateDB) {
// something's wrong
resp.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occured while updating the database!");
}
} else
throw new IOException("The file already exists.");
}
} catch (Exception e) {
resp.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occurred while creating the file : "
+ e.getMessage());
}
} else {
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"Request contents type is not supported by the servlet.");
}
}
i use (on server side ofc)
-commons-fileupload-1.2.2.jar
-commons-io-2.0.1.jar
I don't remember if I needed both but I see them on ../lib so it might be required
I keep some records in a database also .. about my files, that's why there's some database update ..
Powered by vBulletin® Version 4.1.5 Copyright © 2013 vBulletin Solutions, Inc. All rights reserved.