gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:49:46 25 4
gpt4 key购买 nike

如何设置在 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>

最佳答案

只需将所需位置传递到 FileItem#write() 即可按照 Apache Commons FileUpload 自己的 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 会定期自动清理它。

关于java - 如何使用 Commons FileUpload 设置用于存储文件上传的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13528081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com