Results 1 to 4 of 4

Thread: Uploading multiple files in spring MVC application

  1. #1

    Default Uploading multiple files in spring MVC application

    Is there any way to upload (and process) multiple files in Spring mvc application,

    either using Apache-commons file upload or FileUploadBean.? I tried both but no success.


    Any ideas would be appreciated.

    Thanks

  2. #2

    Default

    That is your problem. I have implemented multiple file upload with the Spring MVC without any problem.
    If you want to get some helps, you must provide the details. There are so many different ways to achieve the same goal in Spring. You didn't say anything of your implementation. How others can help you?
    [URL="http://vicina.info"] 新闻,社区新闻,分类广告

  3. #3

    Default

    I might have done some thing wrong. Please see my code below.

    In my recruiting-servlet.xml -------

    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.C ommonsMultipartResolver">
    <property name="maxUploadSize" value="100000"/>
    </bean>

    <bean id="candidateEditController" class="com.wol.spring.CandidateEditController">
    <property name="commandClass" value="com.wol.webapps.recruiting.FileUploadBean" />

    <property name="successView" value="Candidate.html" />
    <property name="candidateDao" ref="candidateDao" />
    <property name="skillsDao" ref="skillsDao" />
    <property name="positionDao" ref="positionDao" />
    <property name="userDao" ref="userDao" />
    <property name="velocityEngine" ref="velocityEngine" />
    <property name="mailSender" ref="mailSender" />


    <property name="redirectOnSuccess" value="true" />
    <property name="redirectProperties">
    <list>
    <value>id</value>
    </list>
    </property>
    </bean>
    -----------------------------
    In FileUploadBean.java--------------


    import org.springframework.web.multipart.MultipartFile;

    public class FileUploadBean
    {

    private MultipartFile file;

    public void setFile(MultipartFile file)
    {
    this.file = file;
    }

    public MultipartFile getFile()
    {
    return file;
    }

    private boolean mTooBig;

    public void setTooBig(boolean aTooBig)
    {
    mTooBig = aTooBig;
    }

    public boolean isTooBig()
    {
    return mTooBig;
    }
    }
    -------------------------------
    In CandidateEditController.java ------

    private int processUploadedFile(HttpServletRequest request, Object command, String id)
    {
    logger.trace("CandidateEditController::processUplo adedFile():Entering...");

    // Setting the command object as FileUploadBean
    FileUploadBean bean = (FileUploadBean) command;

    MultipartFile file = bean.getFile();

    String contenttype = file.getContentType();
    if(file.isEmpty())
    {
    logger.trace("CandidateEditController::processUplo adedFile():File is not attached, exiting with 1 ");
    return 1;
    }

    if (!contenttype.equals("application/octet-stream"))
    {
    if (logger.isDebugEnabled())
    logger.debug("CandidateEditController::processUplo adedFile(): contenttype:= " + contenttype);
    if (file == null)
    {
    // hmm, that's strange, the I did not upload anything
    if (logger.isDebugEnabled())
    logger.debug("CandidateEditController::processUplo adedFile():File is not uploaded.");
    }

    String itemName = file.getOriginalFilename();

    String fileLocation = getServletContext().getRealPath("/") + "uploadedFiles";

    if (logger.isDebugEnabled())
    logger.debug("CandidateEditController::processUplo adedFile():File uploaded is " + file.getOriginalFilename());

    File ff = new File(fileLocation);
    if (ff.mkdir())
    if (logger.isDebugEnabled())
    try
    {
    if (logger.isDebugEnabled())
    logger.debug("CandidateEditController::processUplo adedFile():New directory is created at.." + ff.getCanonicalPath());
    } catch (IOException e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    // Saving uploaded file to local disk location.
    String filePath = fileLocation + "\\" + itemName;

    File f = new File(filePath);

    if (!f.exists())
    try
    {
    f.createNewFile();
    file.transferTo(f);
    } catch (IOException e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    // candidate.setResumeFile(resumeFile)

    /**
    * save File to the database
    *
    */
    candidateDao.saveFileToDB(f, id, filePath);
    logger.trace("CandidateEditController::processUplo adedFile(): File processed, Exiting with 0 ");
    return 0;
    } else
    {
    logger.trace("CandidateEditController::processUplo adedFile(): Executable File can not be processed, Exiting with -1 ");
    return -1;
    }
    }
    --------------------
    This Works pretty good.
    But I am not sure how would I modify or write new code to upload/process multiple files.

    for multiple files uploading I changed FileUploadBean to use array of MultipartFile. and tried to access it into method ProcessFileUpload() in CandiddateEditController. java

    But that didnt work. Please Let me know how do I fix it. That would be really great help.

    --------------------------------------------------------------

    ***************Using apache-Commons file upload :-

    -- Didnt use FileUploadBean, used only simpleFormController with Candidate as Commnad class.
    -- And used following Code:-
    private String processFileUpload(HttpServletRequest request,
    ServletResponse response) {
    logger.debug("ParticipateDataFilter::processFileUp load() entering ");

    // if file is successfully uploaded save this into the directory.

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String filePath = null;
    if (!isMultipart) {
    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() Request IS NOT multipart ");
    } else {

    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() Request IS multipart ");
    FileItemFactory factory = new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(factory);

    List items = null;
    try {

    items = upload.parseRequest(request);
    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() fileItems size "
    + items.size());
    } catch (Exception e) {
    logger
    .debug("ParticipateDataFilter::processFileUpload() Excpetion in Uploadig request is "
    + e.getMessage());
    }
    Iterator itr = items.iterator();
    while (itr.hasNext()) {
    FileItem item = (FileItem) itr.next();
    if (item.isFormField()) {
    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() : This is form field ");
    String paramName = item.getFieldName();
    String paramValue = item.getString();

    /*logger
    .warn("ParticipateDataFilter::processFileUpload(): paramName :- "
    + paramName
    + " paramValue :- "
    + paramValue);*/

    request.setAttribute(paramName, paramValue);
    } else {
    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() This is NOT form field ");

    try {
    String itemName = item.getName(); // String itemName
    // =file.
    // getOriginalFilename
    // ();
    String fileLocation = "/www/tomcat/data/Calculate/Participate";

    File ff = new File(fileLocation);
    if (ff.mkdir())
    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() Directory path here "
    + ff.getCanonicalPath());

    // Saving uploaded file to local disk location.
    filePath = fileLocation + "/" + itemName;
    File savedFile = new File(filePath);
    if (logger.isDebugEnabled())
    logger
    .debug("ParticipateDataFilter::processFileUpload() File path here "
    + filePath);
    if (!savedFile.exists())
    savedFile.createNewFile();
    item.write(savedFile);

    // Kirti:- uncomment this code to restrict upload file
    // to 1MB
    long size = item.getSize();
    if (size > 1000000) {
    request
    .setAttribute("message",
    "File cant be uploaded due to maxium size limit");
    // item.delete();
    savedFile.delete(); // delete file if it exceeds
    // maximum size limit.
    logger
    .warn("ParticipateDataFilter::processFileUpload(): File cant be uploaded due to maxium size limit");
    request.setAttribute("isEmailSent", "false");
    } else {
    logger
    .warn("ParticipateDataFilter::processFileUpload(): File is successfully uploaded");
    request.setAttribute("isEmailSent", "true");
    }
    request.setAttribute("filename", itemName);
    request.setAttribute("fileSize", new Long(size));
    } catch (Exception e) {
    logger
    .debug("ParticipateDataFilter::processFileUpload() Exception in file uploading "
    + e.getMessage());
    }
    }
    }
    }
    return filePath;
    }
    -----At the Line :--- items = upload.parseRequest(request); items.size() is Zero. So doesn't do anything further.


    Please Let me know how do I fix it. That would be really great help. I would appreciate if you can share any working example with me.
    Last edited by kirti_spring; Sep 22nd, 2009 at 01:05 AM.

  4. #4

    Default

    Hi Everyone.

    I'm also tried multiple files upload with spring mvc 3. but i can't achieve that. Please review it my code given below.

    @My Jsp..
    <c:url var="saveUrl" value="/fileUpload/uploading" />

    <form:form action="${saveUrl}" enctype="multipart/form-data" method="post">
    <label for="file">File</label>
    <input id="file" type="file" name="file[]" multiple/>
    <p><button type="submit">Upload<button></p>
    </form:form>

    @Controller

    @RequestMapping(value = "/uploading", method = RequestMethod.POST)
    public String upload(@ModelAttribute("fileUploadBean") FileUploadBean fileUploadBean,BindingResult bindingResult,Model model) throws Exception {

    System.out.println("started uploading");

    if (bindingResult.hasErrors()) {

    for (ObjectError error : bindingResult.getAllErrors()) {
    System.err.println("Error in uploading: " + error.getCode()+ " - " + error.getDefaultMessage());
    }

    return "fileUpload";
    }
    StringBuilder sb = new StringBuilder();

    List<MultipartFile> files = fileUploadBean.getFiles();
    for(MultipartFile f:files)
    sb.append(String.format("File: %s, contains: %s<br/>\n",f.getOriginalFilename(),new String(f.getBytes())));
    String content = sb.toString();

    System.out.println("process uploading::::::"+ content);
    model.addAttribute("content", content);


    return "fileUpload";
    }
    @FileUploadBean

    private List<MultipartFile> files;
    //setter & getter..

    but i'm getting Nullpointer Exception--- List<MultipartFile> files = fileUploadBean.getFiles(); this line..

    So please give me working code ... for this..

    Regards,
    Satheesh

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •