İbrahim Yanık İbrahim Yanık - 4 months ago 26
Ajax Question

File upload change filename in java

File upload change filename in java serclet.How to rename a file (change file name) in java servlet.Rename and save the database.please help me.

my file upload code.

public class AjaxImage extends MNServlet {
private static URLCodec urlcodec = new URLCodec("UTF-8");
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String id = request.getParameter(Plugin.PLUGIN_ID_VARIABLE);

if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> multiparts = upload.parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String road = "";
try {
String name = new File(item.getName()).getName();
String relativeWebPath = "/image";
String absoluteFilePath = request.getServletContext().getRealPath(relativeWebPath);
item.write(new File(absoluteFilePath, FilenameUtils.getName(item.getName())));
request.setCharacterEncoding("UTF-8");
String data = "";
try {
data =urlcodec.decode(request.getParameter("data"), "UTF-8");
} catch (DecoderException e) {
e.printStackTrace();
}

} catch (Exception e) {}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Sam Sam
Answer

You need to change this line

   item.write(new File(absoluteFilePath, FilenameUtils.getName(item.getName())));

Simply switch item.getName() to be the name you would like the file to have once saved.