Всем привет. Учусь программировать на java и столкнулся с проблемой, которую уже давно не могу решить.
Нужно написать web-приложение, куда вводятся данные о человеке, и загружается его фото, и потом отдельно приложение, которое будет показывать информацию о выбранном человеке. Все через базу данных. Затык возник именно в загрузке файла.
Написал форму ввода данных:
Код:
<%--
Document : index
Created on : 15.02.2019, 15:59:57
Author : Proger
--%>
<%@page import="Pack1.Person"%>
<%
request.setCharacterEncoding("UTF-8");
%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Введите данные:</h1>
<form method = "post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/index">
<label>Фотография</label><input type="file" accept="image/*" name="Photo" required="required"><br>
<label>Фамилия <font color = "red">*</font></label><input value="<%=FN%>"type="Text" name="FirstName" ><br>
<label>Имя <font color = "red">*</font></label><input value="<%=LN%>"type="Text" name="LastName" ><br>
<label>Отчество</label><input value="<%=PN%>"type="Text" name="FatherName"><br><br>
<label>Дата рождения<font color = "red">*</font></label><input value="<%=BD%>" type="date" name="birthday" ><br><br>
<label>Телефон<font color = "red">*</font></label><input value="<%=TN%>" type="Tel" name="Telephone" ><br>
<label>E-mail</label><input value="<%=Em%>" type="email" name="mail" ><br>
<label>Город<font color = "red">*</font></label><select value="<%=C%>" name="City" required="required">
<option value="77">Москва</option>
<option value="78">Санкт-Петербург</option>
<option value="29">Архангельск</option>
<option value="30">Астрахань</option>
<option value="31">Белгород</option>
<option value="32">Брянск</option>
<option value="33">Владимир</option>
<option value="34">Волгоград</option>
</select><br><br>
<label>Тип занятости<font color = "red">*</font></label><select value="<%=W%>" name="Work" required="required">
<option value="None">Не работаю</option>
<option value="Pensioner">Пенсионер</option>
<option value="Student">Учащийся</option>
<option value="IP">Индивидуальный предприниматель</option>
<option value="Worker">Полная занятость(по ТД)</option>
<option value="Military">Военнослужащий по контракту</option>
</select><br>
<input type="reset"> <input type="submit">
</form>
</body>
</html>
Опустим все поля кроме ввода файла, там все просто.
Создал сервлет:
Код:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Pack1;
import java.io.File;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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("/index")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class indexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String SAVE_DIRECTORY = "uploadDir";
public indexServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/jsps/index.jsp");
dispatcher.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String description = request.getParameter("description");
System.out.println("Description: " + description);
// Gets absolute path to root directory of web app.
String appPath = request.getServletContext().getRealPath("");
appPath = appPath.replace('\\', '/');
// The directory to save uploaded file
String fullSavePath = null;
if (appPath.endsWith("/")) {
fullSavePath = appPath + SAVE_DIRECTORY;
} else {
fullSavePath = appPath + "/" + SAVE_DIRECTORY;
}
System.out.println("Path: " + fullSavePath);
// Creates the save directory if it does not exists
File fileSaveDir = new File(fullSavePath);
if (!fileSaveDir.exists()) {
System.out.println("fullSavePath will be created");
fileSaveDir.mkdir();
System.out.println("fullSavePath has been created");
}
// Part list (multi files).
int i = 0;
//request.getParameter("FirstName");
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
if (fileName != null && fileName.length() > 0) {
String filePath = (fullSavePath + File.separator + fileName);
// Write to file
/*76*/ part.write(fileName);
}
}
// Upload successfully!.
response.sendRedirect(request.getContextPath() + "/uploadFileResults");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorMessage", "Error: " + e.getMessage());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsps/index.jsp");
dispatcher.forward(request, response);
}
}
private String extractFileName(Part part) {
// form-data; name="file"; filename="C:\file1.zip"
// form-data; name="file"; filename="C:\Note\file2.zip"
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
// C:\file1.zip
// C:\Note\file2.zip
String clientFileName = s.substring(s.indexOf("=") + 2, s.length() - 1);
clientFileName = clientFileName.replace("\\", "/");
int i = clientFileName.lastIndexOf('/');
// file1.zip
// file2.zip
return clientFileName.substring(i + 1);
}
}
return null;
}
}
Честно признаюсь, что где-то нашел (но не могу вспомнить где) этот сервлет, и попытался разобраться. Все вроде почти понятно, но вот только при попытки записать в файл (строка 76) он пытается записать в несуществующий файл. Пробовал вместо имени ввести абсолютный адрес и перед этим создавать файл, но не помогло, так как к адресу по умолчанию добавляет тот, что я ввел в качестве имени. Как лучше сделать?