4

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

我正在使用commons.fileupload,就目前而言,我可以将多个.tmp文件存储到,catalina_base/temp但是,我的目标是将上传的文件夹以其原始形式存储到d:\\dev\\uploadservlet\\web\\uploads

我知道这个问题含糊不清,但老实说,我使用 servlet 的时间很短,我还不了解大局,任何关于代码或教程链接的建议将不胜感激。

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

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();
    }
}
}

...它从这个 HTML 表单中获取信息:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Upload Page</title>


    <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.24.custom.css">
    <link rel="stylesheet" type="text/css" href="css/style.css"

    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jquery-ui.js"></script>
    <script type="text/javascript" src="uploadFunctions.js"></script>

</head>

<body>
    <div>
        <form name="uploadForm" id="uploadForm" action="test" method="post" enctype="multipart/form-data">
            <input type="hidden" name="hiddenfield1" value="ok">
            <h3>Files to upload:</h3>
            <input type="file" size="50" name="file1">
            <span id="file1Progress">-</span>
            <br/>
            <a href="javascript:previewFile(1)">Preview</a>
            <br/>
            <br/>

            <input type="file" size="50" name="file2">
            <span id="file2Progress">-</span>
            <br/>
            <a href="javascript:previewFile(2)">Preview</a>
            <br/>
            <br/>

            <input type="file" size="50" name="file3">
            <span id="file3Progress">-</span>
            <br/>
            <a href="javascript:previewFile(3)">Preview</a>
            <br/>
            <br/>

            <input type="file" size="50" name="file4">
            <span id="file4Progress">-</span>
            <br/>
            <a href="javascript:previewFile(4)">Preview</a>
            <br/>
            <br/>

            <input type="file" size="50" name="file5">
            <span id="file5Progress">-</span>
            <br/>
            <a href="javascript:previewFile(5)">Preview</a>
            <br/>
            <br/>
            <input type="button" value="Upload" id="submitButton" onclick="uploadForm.submit();doProgress();">
            <br/>
            <br/>
        </form>

        <div class="progBar">                
            File number: <span id="fileText">-</span> is being uploaded.<br/> 
            <br/>
            <progress id="progressBar" value="0" max="100"></progress><br/>
            Upload of all files is: <span id="progressText">-</span>% complete.<br/>
        </div>
    </div>
</body>
</html>
4

3 回答 3

2

你见过javadocDiskFileItemFactory吗?有一种方法setRepository 需要File参数(将存储临时文件的文件夹)。

所以试试这个:

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

当您解析表单字段时,您可以将这些文件保存在任何您想要的地方。

希望它会帮助你。

于 2012-11-23T11:32:50.087 回答
2

只需按照 Apache Commons FileUpload's own users guideFileItem#write()中描述的常用方式将所需位置传递给方法。

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

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 会定期自动清理它。

于 2012-11-23T16:03:58.700 回答
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>");
            }

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

于 2012-11-23T11:32:40.860 回答