这是servlet代码
package servlets;import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;public class FileUpload extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator items;
try {
items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
if (!item.isFormField()) {
// 取出上传文件的文件名称
String name = item.getName();
String fileName = name.substring(
name.lastIndexOf('\\') + 1, name.length());
String path = request.getRealPath("\\") + fileName;
// 上传文件
File uploadedFile = new File(path);
item.write(uploadedFile); // 打印上传成功信息
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
out.print("<font size='2'>上传的文件为:" + name + "<br>");
out.print("保存的地址为:" + path + "</font>");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
这是JSP代码
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<title>commonfileupload上传文件示例</title>
</head>
<body>
commonfileupload上传文件示例
<br>
<form method="post" action="FileUpload" ENCTYPE="multipart/form-data">
文件:
<input type="file" name="file">
<input type="submit" value="上传" name="submit">
</form>
</body>
</html>
现在上传功能可以实现  但是我想把它存到指定的文件夹里而不是根目录,然后文件能够重命名,需要怎么改动。。

解决方案 »

  1.   

     String path = request.getRealPath("\\路径\\路径...") + 你想要的文件名字;
      

  2.   

    //String name = item.getName();
    //String fileName = name.substring(
                                    name.lastIndexOf('\\') + 1, name.length());这二句不要好了呀
    String path = request.getRealPath("\\") + "xxx";
      

  3.   

    可以根据上传文件的文件名对文件夹进行命名然后    String filepath = request.getRealPath("file") + "\\" + "xxx"
        File dirFile = new File(filepath);
        if(!(dirFile.exists()) && !(dirFile.isDirectory())){
            dirFile.mkdirs();
        }文件重命名只需要将后缀截取掉,加上想要的名字就好了,网上很多是根据日期命名,不过我觉得还是依次在后面累加数字比较好,目前也在找方法,lz有好方法吗?