如何使用Commons FileUpload设置用于存储文件上载的文件夹

时间:2012-11-23 11:23:23

标签: java servlets file-upload apache-commons-fileupload

如何设置在TOMCAT服务器上存储文件上传位置的位置?

我正在使用commons.fileupload,因此我可以将多个.tmp文件存储到catalina_base/temp但是,我的目的是将上传的文件夹以原始格式存储到{{ 1}}

我知道这个问题很模糊,但说实话,我一直在使用servlet这么短的时间,我还不了解大图,任何代码建议或教程链接都将不胜感激

我处理上传的servlet代码如下:

d:\\dev\\uploadservlet\\web\\uploads

...它从这个HTML表单得到了它的信息:

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oreilly.servlet.MultipartRequest;

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 TestServlet extends HttpServlet {

private static final long serialVersionUID = 1L;    
    public static final long MAX_UPLOAD_IN_MEGS = 5;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

            //This is the folder I want to use!!
            //String uploadFolder = "d:\\dev\\uploadservlet\\web\\uploads";

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("Upload unsuccessful<br/>");
        return;
    }

    out.println("The following was uploaded:<br/>");

    FileItemFactory factory = new DiskFileItemFactory();     
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_UPLOAD_IN_MEGS * 1024 * 1024);


    TestProgressListener testProgressListener = new TestProgressListener();
    upload.setProgressListener(testProgressListener);

    HttpSession session = request.getSession();
    session.setAttribute("testProgressListener", testProgressListener);

    try {
        List<FileItem> fields = upload.parseRequest(request);
        out.println("Number of fields: " + fields.size() + "<br/><br/>");
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            out.println("No fields found");
            return;
        }
        out.println("<table border=\"1\">");
        while (it.hasNext()) {
            out.println("<tr>");
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + 
                        "<br/>STRING: " + fileItem.getString()
                        );
                out.println("</td>");
            } else {
                out.println("<td>file form field</td><td>FIELDNAME: " + fileItem.getFieldName() +//                     <br/>STRING: " + fileItem.getString() +
                        "<br/>NAME: " + fileItem.getName() +
                        "<br/>CONTENT TYPE: " + fileItem.getContentType() +
                        "<br/>SIZE (BYTES): " + fileItem.getSize() +
                        "<br/>TO STRING: " + fileItem.toString()
                        );
                out.println("</td>");
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (FileUploadException e) {
        out.println("Error: " + e.getMessage());
        e.printStackTrace();
    }
}
}

3 个答案:

答案 0 :(得分:2)

你见过DiskFileItemFactory的javadoc吗?有一个方法setRepository,它接受​​File参数(将存储临时文件的文件夹)。

所以试试这个:

    FileItemFactory factory = 
       new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, 
                               new File("d:\\dev\\uploadservlet\\web\\uploads"));

解析表单字段时,可以将此文件保存在任何位置。

希望它会对你有所帮助。

答案 1 :(得分:2)

只需按照Apache Commons FileUpload自己的FileItem#write()中所述的常规方式将所需位置传递到users guide方法。

首先在servlet的init()中初始化上传文件夹。

private File uploadFolder;

@Override
public void init() throws ServletException {
    uploadFolder = new File("D:\\dev\\uploadservlet\\web\\uploads");
}

(如果需要,您可以从环境变量或属性文件中获取此信息)

然后从上传文件的文件名中提取基本名称和扩展名,并根据它生成一个唯一的文件名(当然,当其他人通过巧合上传文件时,您不希望先前上传的文件被覆盖同名,对吗?):

String fileName = FilenameUtils.getName(fileItem.getName());
String fileNamePrefix = FilenameUtils.getBaseName(fileName) + "_";
String fileNameSuffix = "." + FilenameUtils.getExtension(fileName);
File file = File.createTempFile(fileNamePrefix, fileNameSuffix, uploadFolder);
fileItem.write(file);
System.out.println("File successfully saved as " + file.getAbsolutePath());
// ...

(请注意,File#createTempFile()并不一定意味着它是一个临时文件,会在某个时间自动删除,不,在这种特殊情况下,它只是被用作工具的顺序在给定文件夹中生成具有保证唯一文件名的文件)

FilenameUtils由Apache Commons IO提供,您应该已经安装了它,因为它是Commons FileUpload的依赖项。


请注意,您绝对不应将其设置为DiskFileItemFactory构造函数的第二个参数,如其他答案所示。如其javadoc中明确提到的,这表示当超过阈值大小时(即,当它们变得太大而不能完全保存在服务器的存储器中时)存储上载文件的临时磁盘文件系统位置。此位置绝对不是上传文件的永久存储位置。它将由Commons FileUpload定期自动清理。

答案 2 :(得分:0)

您正在使用FileUpload来管理上传。所以在您的代码中,您只需定义一个文件并将数据写入其中。我只会复制相关部分并添加到其中:

if (isFormField) {
                out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + 
                        "<br/>STRING: " + fileItem.getString()
                        );
                out.println("</td>");
            } else {

              //write the file
              String myPath= ..... 
              File f=new File(myPath);
              fileItem.write(f); 

                out.println("<td>file form field</td><td>FIELDNAME: " + fileItem.getFieldName() +//                     <br/>STRING: " + fileItem.getString() +
                        "<br/>NAME: " + fileItem.getName() +
                        "<br/>CONTENT TYPE: " + fileItem.getContentType() +
                        "<br/>SIZE (BYTES): " + fileItem.getSize() +
                        "<br/>TO STRING: " + fileItem.toString()
                        );
                out.println("</td>");
            }

重要提示:确保您对写入文件的文件夹具有写入权限。