如何使用Commons FileUpload来设置存储文件上传的文件夹 [英] How do I set the folder for storing file uploads using Commons FileUpload

查看:163
本文介绍了如何使用Commons FileUpload来设置存储文件上传的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用 commons.fileupload 如何设置位置以在TOMCAT服务器上存储文件上传的位置? c $ c>,因此,我可以将多个 .tmp 文件存储到 catalina_base / temp ,但是,我的目标是将上传的文件夹以原始格式存储到 d:\\dev\\\\\\\\\\\\\\\\\\\\\\\\\\\\ >

我知道这个问题是模糊的,但说实话,我一直在使用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;
导入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;
$ b $ public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException {
doPost(request,response);

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

//这是我想要使用的文件夹!
// String uploadFolder =d:\\dev\\uploadservlet\\web\\uploads;

boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if(!isMultipartContent){
out.println(上传失败< br />);
return;


out.println(以下是上传的:< 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);

尝试{
列表< 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 \>); (it.hasNext()){
out.println(< tr>);
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if(isFormField){
out.println(< td>常规表单字段< / td>< td> FIELD名称:+ fileItem.getFieldName()+
< ; br /> STRING:+ fileItem.getString()
);
out.println(< / td>);
} else {
out.println(< td>文件表单字段< / td>< td> FIELDNAME:+ fileItem.getFieldName()+ //< br /> STRING :+ fileItem.getString()+
< br />名称:+ 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-Typecontent =text / html; charset = ISO-8859-1>
< title>上传页面< / title>


< link rel =stylesheettype =text / csshref =css / ui-lightness / jquery-ui-1.8.24.custom.css>
< link rel =stylesheettype =text / csshref =css / style.css

< script type =text / javascriptsrc =js /jquery.js\"></script>
< script type =text / javascriptsrc =js / jquery-ui.js>< / script>
< script type =text / javascriptsrc =uploadFunctions.js>< / script>

< / head>

< body>
< div>
< form name =uploadFormid =uploadFormaction =testmethod =postenctype =multipart / form-data>
< input type =hiddenname =hiddenfield1value =ok>
< h3>要上载的档案:< / h3>
< input type =filesize =50name =file1>
< span id =file1Progress> - < / span>
< br />
< a href =javascript:previewFile(1)>预览< / a>
< br />
< br />

< input type =filesize =50name =file2>
< span id =file2Progress> - < / span>
< br />
< a href =javascript:previewFile(2)>预览< / a>
< br />
< br />

< input type =filesize =50name =file3>
< span id =file3Progress> - < / span>
< br />
< a href =javascript:previewFile(3)>预览< / a>
< br />
< br />

< input type =filesize =50name =file4>
< span id =file4Progress> - < / span>
< br />
< a href =javascript:previewFile(4)>预览< / a>
< br />
< br />

< input type =filesize =50name =file5>
< span id =file5Progress> - < / span>
< br />
< a href =javascript:previewFile(5)>预览< / a>
< br />
< br />
< input type =buttonvalue =Uploadid =submitButtononclick =uploadForm.submit(); doProgress();>
< br />
< br />
< / form>

< div class =progBar>
档案号码:< span id =fileText> - < / span>正在上传。< br />
< br />
< progress id =progressBarvalue =0max =100>< / progress>< br />
上传的所有文件是:< span id =progressText> - < / span>%完成。
< / div>
< / div>
< / body>
< / html>


解决方案

只需将所需的位置传递给 FileItem#write() 按照Apache Commons FileUpload自己的用户指南中所述的常用方法。首先初始化你的servlet的 init()中的上传文件夹。

 私人档案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的间隔。


How do I set to location of where to store file uploads on a TOMCAT server?

I am using commons.fileupload and as it stands I am able to store multiple .tmp files to catalina_base/temp however, my aim is to store the uploaded folders in their original form to d:\\dev\\uploadservlet\\web\\uploads

I know this question is vague but to be honest I've been working with servlets for such a short amount of time and I don't yet understand the big picture, any suggestions of code or links to tutorials would be greatly appreciated.

My servlet code which handles the uploads is as follows:

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

...and it get's it's information from this HTML form:

<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>

解决方案

Just pass the desired location into FileItem#write() method the usual way as described in the Apache Commons FileUpload's own users guide.

First initialize the upload folder in the init() of your servlet.

private File uploadFolder;

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

(you can if necessary get this information from an environment variable or a properties file)

Then extract the base name and extension from the filename of the uploaded file and generate an unique filename based on it (you of course don't want that a previously uploaded file get overwritten when someone else by coincidence uploads a file with the same name, right?):

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());
// ...

(note that the File#createTempFile() doesn't necessarily mean that it's a temporary file which will be auto-deleted at some time, no, it's in this particular case just been used as a tool in order to generate a file with a guaranteed unique filename in the given folder)

The FilenameUtils is provided by Apache Commons IO which you should already have installed as it's a dependency of Commons FileUpload.


Note that you should absolutely not set it as 2nd argument of DiskFileItemFactory constructor as suggested by the other answer. This represents, as clearly mentioned in its javadoc, the temporary disk file system location to store uploaded files when they exceed the threshold size (i.e. when they become too large to hold entirely in server's memory). This location is absolutely not intented as a permanent storage location for uploaded files. It will be auto-cleaned up at intervals by Commons FileUpload.

这篇关于如何使用Commons FileUpload来设置存储文件上传的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆