0

I have a jsp code to upload a file from multipart/form-data..

upload.jsp

 <%@ page import="java.io.*"%>
 <%@page import="com.oreilly.servlet.MultipartRequest" %>
 <%@ page import="java.util.*" %>
 <%
try
   {
    MultipartRequest mrequest = new MultipartRequest(request, "C:/uploads");
    String file_name=mrequest.getParameter("fname");//recieve fname
    Enumeration files = mrequest.getFileNames();

    while(files.hasMoreElements() )
      {
        String upload = (String)files.nextElement();
         String filename = mrequest.getFilesystemName(upload);
        System.out.println(filename);
    }
}
catch(Exception ex)
{
System.out.println("Error creating file: " + ex );
}%>

test.html

<HTML>
<BODY>
<FORM ENCTYPE="multipart/form-data" ACTION="upload.jsp" METHOD="POST">
choose file  <input type="file" name="file">
name for file <input type="text" name="fname">
 <input type="submit" value="submit">
</FORM>
</BODY>

This code works and uploads file to c:/upload directory. But what if we want to change the name of file while uploading to the name other than its original name that receive from form. How can it be done, as it receives the original filename as an enumeration?

Ankit Wasankar
  • 145
  • 1
  • 12
  • There are many similar questions on SO alredy. 'http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet' Or even 'http://www.tutorialspoint.com/jsp/jsp_file_uploading.htm' – Sushan Ghimire May 12 '13 at 09:31

1 Answers1

0

change your code like this .

while(files.hasMoreElements())
{
    String upload=(String)files.nextElement();

    File filename=new File(mrequest.getOriginalFileName(upload));

    filename.renameTo("newName");
}

in the place of newName give your desired value :)

sme
  • 4,023
  • 3
  • 28
  • 42
SABER
  • 373
  • 6
  • 17