优秀的社区!:) 我给你带来一个查询。我正在尝试使用 Java 制作一个接收文本、日期和文件的表单。文件上传到服务器,获取文件的链接,并将其存储在数据库中。
首先我已经完成了将日期和文本上传到数据库的部分,现在我正在尝试添加文件上传到服务器的部分,但由于某种原因我没有这样做。
这是我的代码:
形式:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
String usuario = "";
HttpSession sesionOk = request.getSession();
if (sesionOk.getAttribute("usuario") == null) { //Verifica que este logueado
%>
<jsp:forward page="login.jsp"/>
<%
} else {
usuario = (String)sesionOk.getAttribute("usuario");
}
%>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="editar.css">
<title>Legislatura Pro Cordoba Sur</title>
</head>
<body>
<header> MENU -> <%=usuario%> - <a href="cerrarsesion.jsp">Cerrar Sesion</a> </header>
<div id="mainContainer">
<FORM id="formulario" action="agregarComentarioServlet?codigo=<%= request.getParameter("codigo") %>" method="POST">
<table id="tablaForm">
<tr>
<td class="labelD">Fecha:</td> <td><input type="date" size=30 value="" name="fecha"/></td>
</tr>
<tr>
<td class="label">Texto:</td><td colspan="3"><input type="text" size=80 value="" name="texto"/></td>
</tr>
<tr>
<td class="label">Agregar adjunto</td><td><input type="file" size=30 value="" name="filename"/></td>
</tr>
<tr>
<td colspan="4" class="Cabecera"><input class="boton" type="submit" name="agregar" value="Agregar"/></td>
</tr>
</table>
</FORM>
<br>
<br>
<br> ${requestScope.error}
</div>
<footer>Pro Cordoba Sur - 2016</footer>
</body>
</html>
小服务程序:
import com.mysql.jdbc.Connection;
import java.io.File;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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.HttpSession;
import javax.servlet.http.Part;
/**
*
* @author Facu
*/
@WebServlet(urlPatterns = {"/agregarComentarioServlet"})
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class agregarComentarioServlet extends HttpServlet {
private static final String UPLOAD_DIR = "archivos";
Connection connection;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sesionOk = request.getSession();
if ( (sesionOk.getAttribute("usuario") == null) ){//Verifica que este logueado
request.getRequestDispatcher("login.jsp").forward(request, response);
}
if(request.getParameter("codigo")==null){
String error="<div class=error>Intentando agregar un comentario sin codigo</div>";
request.setAttribute("error", error);
request.getRequestDispatcher("menuServlet").forward(request, response);
}
try {
connectDB();
} catch (SQLException ex) {
String error="<div class=error>Error al conectar con la base de datos</div>";
request.setAttribute("error", error);
request.getRequestDispatcher("menu.jsp").forward(request, response);
} catch (ClassNotFoundException ex) {
String error="<div class=error>Driver no cargado</div>";
request.setAttribute("error", error);
request.getRequestDispatcher("menu.jsp").forward(request, response);
}
subirArchivo(request, response);
PreparedStatement preparedStmt=null;
try {
String sql="INSERT INTO comentario (fecha, codigo, texto) VALUES (?,?,?)";
String fecha= request.getParameter("fecha");
String codigoStr=request.getParameter("codigo");
int codigo=Integer.parseUnsignedInt(codigoStr);
String texto=request.getParameter("texto");
preparedStmt = connection.prepareStatement(sql);
preparedStmt.setString(1, fecha);
preparedStmt.setInt(2, codigo);
preparedStmt.setString(3, texto);
preparedStmt.execute();
request.getRequestDispatcher("editarServlet?codigo="+codigo).forward(request, response);
} catch (SQLException ex) {
String error="<div class=error>La consulta es incorrecta</div>";
request.setAttribute("error", error);
request.getRequestDispatcher("menu.jsp").forward(request, response);
}catch (NumberFormatException ex){
String error="<div class=error>El estado es invalido</div>";
request.setAttribute("error", error);
request.getRequestDispatcher("menuServlet").forward(request, response);
}finally{
try { if (preparedStmt != null) preparedStmt.close(); } catch (Exception e) {};
try { if (connection != null) connection.close(); } catch (Exception e) {};
}
}
void connectDB() throws SQLException, ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver"); //Carga el driver
String url = "jdbc:mysql://127.0.0.1:3306/expediente";
String username = "root";
String password = "123456";
connection = (Connection) DriverManager.getConnection(url, username, password);
}
String subirArchivo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
try {
// gets absolute path of the web application
String applicationPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(uploadFilePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
fileName = (String) getFileName(part);
part.write(uploadFilePath + File.separator + fileName);
}
return fileName;
} catch (IOException | ServletException ex) {
String error="<div class=error>Error al subir el archivo</div>";
request.setAttribute("error", error);
request.getRequestDispatcher("menu.jsp").forward(request, response);
}
return "";
}
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
这是给我的错误:
java.lang.IllegalStateException: No puedo reenviar después de que la respuesta se haya llevado a cabo.
agregarComentarioServlet.processRequest(agregarComentarioServlet.java:73)
agregarComentarioServlet.doPost(agregarComentarioServlet.java:168)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
我澄清一下上传文件到服务器的部分不是我的,事实是我不知道怎么做,所以用这个教程指导我:http: //www.journaldev.com/2122/servlet- 3-文件上传-multipartconfig-part
无论如何,它并没有很好地解释它是如何工作的,而且我并不真正理解我做了什么(这就是它失败的原因:/)所以如果有人可以解释并帮助我纠正错误,我将非常感激。
更新:
遵循此帮助: https ://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet
我已经设法将文件上传到服务器。这里的代码:
String subirArchivo(int codigo, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Part filePart = request.getPart("archivo"); // Obtiene el archivo
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
//InputStream fileContent = filePart.getInputStream(); //Lo transforma en InputStream
String path="/archivos/";
File uploads = new File(path); //Carpeta donde se guardan los archivos
uploads.mkdirs(); //Crea los directorios necesarios
File file = File.createTempFile("cod"+codigo+"-", "-"+fileName, uploads); //Evita que hayan dos archivos con el mismo nombre
try (InputStream input = filePart.getInputStream()){
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
return file.getPath();
}
但是,我在保存文件的位置时遇到问题...如果在字符串路径中,我输入“/files/”,文件将上传到 C://files 因此我无法下载它,因为那个tomcat没有访问那个目录(我不知道怎么上传到那里...)我尝试下载: http://localhost:8080/archivos/comentario.csv 它告诉我资源是无法使用。
如果相反,我在路径中放置相对目录:“./files/” 该文件将上传到我的 tomcat 文件夹内的 bin 目录。而且我也无法下载。我应该如何将它上传到我有权访问的文件夹中?
我在以下位置找到了解决方案: https ://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet
我有以下代码:
文件上传到 C:\files。所以你需要添加:
到标签内的 tomcat 配置的 server.xml 文件
<host>
定义保存文件的完整地址路径
前任:
在服务器上创建此目录很重要
然后在Java中做:
然后将您的文件转换为 byte[] 您可以执行以下操作:
然后它将路径和名称保存在数据库中
前任:
那里有每个案例的名称,您可以上传它们并处理 Java、BBDD 或任何它涉及的东西;)(在尝试之前或之后,这取决于您的喜好和您的喜好)