jsp一个表单提交多个图片上传服务器,路径保存到数据库
时间: 2023-05-21 07:02:35 浏览: 125
您可以使用HTML5的FormData对象来实现多文件上传,然后使用Ajax将数据发送到服务器。在服务器端,您可以使用Java的Servlet来处理上传的文件,并将文件路径保存到数据库中。以下是一个简单的示例代码:
HTML代码:
```html
<form id="myForm" enctype="multipart/form-data">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="button" value="Upload" onclick="uploadFiles()">
</form>
```
JavaScript代码:
```javascript
function uploadFiles() {
var form = document.getElementById("myForm");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", "uploadServlet", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send(formData);
}
```
Java代码:
```java
@WebServlet("/uploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String file1Path = saveFile(request.getPart("file1"));
String file2Path = saveFile(request.getPart("file2"));
// 将文件路径保存到数据库中
// ...
response.getWriter().write("Files uploaded successfully!");
}
private String saveFile(Part part) throws IOException {
String fileName = getFileName(part);
String filePath = "C:/uploads/" + fileName;
part.write(filePath);
return filePath;
}
private String getFileName(Part part) {
String contentDisposition = part.getHeader("content-disposition");
String[] tokens = contentDisposition.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length() - 1);
}
}
return "";
}
}
```
请注意,此示例代码仅供参考,您需要根据自己的需求进行修改和优化。
阅读全文