java图片上传至本地
时间: 2023-10-14 18:26:11 浏览: 134
java图片上传
4星 · 用户满意度95%
以下是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
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "uploads";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String applicationPath = request.getServletContext().getRealPath("");
String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
File fileUploadDirectory = new File(uploadFilePath);
if (!fileUploadDirectory.exists()) {
fileUploadDirectory.mkdirs();
}
Part filePart = request.getPart("file");
String fileName = getFileName(filePart);
String savePath = uploadFilePath + File.separator + fileName;
InputStream inputStream = filePart.getInputStream();
Path filePath = Paths.get(savePath);
Files.copy(inputStream, filePath);
response.getWriter().println("File " + fileName + " has been 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;
}
}
```
解释:
- `@WebServlet("/upload")` 注释指定了上传文件的路径。
- `@MultipartConfig` 注释指定了此 Servlet 支持多部分表单数据。
- `doPost()` 方法从请求中获取上传的文件并将其保存到指定的目录中。
- `getFileName()` 方法从请求头中获取文件名。
上传表单可以使用以下 HTML:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
```
此代码将上传的文件保存到 Web 应用程序目录的 `uploads` 文件夹中。可以根据需要更改上传文件的目录。
阅读全文