java目录里上传的代码
时间: 2023-11-26 10:03:52 浏览: 30
以下是 Java 中实现服务器目录上传文件的示例代码:
```java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/upload")
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 2, // 2 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 50 // 50 MB
)
public class FileUploadServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "uploads";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 创建上传文件夹
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 处理上传的文件
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
if (fileName != null && !fileName.isEmpty()) {
String filePath = uploadPath + File.separator + fileName;
File file = new File(filePath);
try (InputStream inputStream = part.getInputStream()) {
Files.copy(inputStream, file.toPath());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
response.sendRedirect(request.getContextPath() + "/success.jsp");
}
private String extractFileName(Part part) {
String contentDisposition = part.getHeader("content-disposition");
String[] items = contentDisposition.split(";");
for (String item : items) {
if (item.trim().startsWith("filename")) {
return item.substring(item.indexOf("=") + 2, item.length() - 1);
}
}
return null;
}
}
```
这段代码实现了在服务器上创建名为 "uploads" 的上传文件夹,将用户上传的文件保存到该文件夹中。该代码使用了 Java Servlet 3.0 提供的 `@MultipartConfig` 注解,用于指定上传文件的大小限制。在上传文件时,该代码会遍历所有上传的文件,将每个文件保存到上传文件夹中。其中,`extractFileName` 方法用于从 HTTP 请求头中获取上传文件的文件名。