java上传xml文件
时间: 2023-10-14 18:10:36 浏览: 105
以下是Java上传XML文件的示例代码:
```java
import java.io.File;
import java.io.IOException;
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
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "uploads";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取上传文件的目录
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
//获取上传的文件
Part filePart = request.getPart("file");
String fileName = getFileName(filePart);
Path filePath = Paths.get(uploadPath, fileName);
Files.copy(filePart.getInputStream(), filePath);
//处理上传的文件
//TODO
response.getWriter().append("File uploaded successfully!");
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : partHeader.split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
```
在上面的代码中,我们使用了Servlet 3.0提供的@MultipartConfig注解来支持文件上传。该注解表明该Servlet支持文件上传,并且指定上传文件的临时目录。在doPost方法中,我们首先获取上传文件的目录,如果该目录不存在则创建。然后获取上传的文件,将其保存到指定的目录中。最后我们可以在处理上传的文件之前,将上传的文件名输出到控制台上。
阅读全文