这是上传文件代码的相关java代码,我需要为文件名添加时间戳,然后将其上传到特定目录
public class Upload extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
System.out.println(this.getClass().getName());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//boolean MultipartRequest;
//String PrintWriter;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
MultipartRequest multipartRequest = new MultipartRequest(request, "/home/hadoop/Desktop");
out.println("succcesfully uploaded");
}
public void destroy() {
System.out.println(this.getClass().getName());
}
}
<html>
<body>
<form action="UploadFile" method="post" enctype="multipart/form-data">
Selectfile:
<input type="file" name="filename">
<br/>
<input type="submit" value="Upload">
</form>
</body>
</html>
答案 0 :(得分:3)
MultipartRequest包含文件重命名策略。
为了避免冲突并对文件放置有很好的控制,有一种构造函数可以采用可插入的FileRenamePolicy实现。特定策略可以选择在文件写入之前重命名或更改文件的位置。
MultipartRequest(javax.servlet.http.HttpServletRequest request,
java.lang.String saveDirectory,
int maxPostSize,
FileRenamePolicy policy)
注意:由于声誉不佳,我无法添加评论,因此不得不将此作为答案。不要低估这一点,而是纠正或评论。
答案 1 :(得分:1)
简单地将"_" + System.currentTimeMillis()
连接到文件名?
如果不是你希望得到的可理解时间戳的毫秒,只需使用另一个答案中显示的DateFormat。
使用Java EE&gt; = 6:
@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String applicationPath = request.getServletContext().getRealPath("");
String uploadFilePath = applicationPath + File.separator + "uploads";
File fileSaveDir = new File(uploadFilePath);
if (!fileSaveDir.exists()) { fileSaveDir.mkdirs(); }
String fileName = null;
for (Part part : request.getParts()) {
fileName = getFileName(part) + "_" + System.currentTimeMillis(); // <----- HERE
part.write(uploadFilePath + File.separator + fileName);
}
request.setAttribute("message", fileName + " File uploaded successfully!");
getServletContext().getRequestDispatcher("/response.jsp").forward(
request, response);
}
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}
}
代码是this article
中的代码的分支答案 2 :(得分:0)
获取当前日期和时间,并在上传时将其附加到您的文件名。
private final static String getDateTime()
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT")); // mention your timezone
return df.format(new Date());
}
现在将返回的字符串附加到文件名中。