gpt4 book ai didi

java - 使用JSP、servlet和ajax上传文件而不设置表单的action属性

转载 作者:行者123 更新时间:2023-12-02 09:39:26 25 4
gpt4 key购买 nike

我正在尝试使用 JSP 和 servlet 上传文件。这是 JSP 代码:

 <script type="text/javascript">
function UploadFile() {
var paramater = "hello";
$.post('fileUploadServlet', {param : paramater});
}
</script>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="datafile" size="50" /> <br />
<input type="submit" value="Upload File" onclick="UploadFile()" />
<input type="hidden" name="type" value="upload">
</form>

servlet 代码如下所示:

public class fileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
System.out.println(request.getContentType());
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (!isMultipart) {
return;
}

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Sets the size threshold beyond which files are written directly
// to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);

// Sets the directory used to temporarily store files that are
// larger
// than the configured size threshold. We use temporary directory
// for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// String uploadFolder = System.getProperty("java.io.tmpdir") +
// File.separator + UUID.randomUUID().toString() + File.separator +
// "abc.xml";
// FileUtils.createFileParent(uploadFolder);

// constructs the folder where uploaded file will be stored
String uploadFolder = "C:\\Users\\IBM_ADMIN\\workspace_new\\Trees\\WebContent\\UploadedFiles";

// String uploadFolder = getServletContext().getRealPath("")
// + File.separator + DATA_DIRECTORY;

System.out.println("uploadFolder : " + uploadFolder);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);

try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();

String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
response.getWriter().write("Work done");
}
}

} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}

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

}

当我调试时,我发现它在 if(!isMultipart) 行失败,并且 servlet 返回并且无法上传任何文件。我尝试打印 request.getContentType(),它打印为 application/x-www-form-urlencoded; charset=UTF-8 而不是 multipart/form-data。我哪里出错了?

提前致谢!

最佳答案

在定义 Servlet 之前添加以下代码行,要处理多部分/表单数据提交,您必须使用多部分注释

导入javax.servlet.annotation.MultipartConfig;
导入javax.servlet.annotation.WebServlet;

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,//2MB
最大文件大小 = 1024 * 1024 * 10,//10MB
maxRequestSize = 1024 * 1024 * 50)

@WebServlet("/ServletName")

关于java - 使用JSP、servlet和ajax上传文件而不设置表单的action属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892756/

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