【问题标题】:Files uploaded to the local server. How to save file path and file name into the mysql database using jsp ?文件上传到本地服务器。如何使用 jsp 将文件路径和文件名保存到 mysql 数据库中?
【发布时间】:2017-04-17 05:04:40
【问题描述】:

我已尝试将文件上传到 c 本地驱动器中,但我必须将该文件名和文件路径插入 MySql 数据库。下面的代码将文件存储到 c:local 文件夹中,但文件路径和文件名没有存储到数据库中。请更正我的代码。

<%@ page import="java.io.*,java.sql.*,java.util.zip.*" %>
<%
String saveFile="";
String contentType = request.getContentType();
if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File("C:/UploadedFiles/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%>
<br>
<%out.println(saveFile);%>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/test";
PreparedStatement psmnt = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "12345");
psmnt = connection.prepareStatement("insert into file_upload(file_path,file_name,category,tags) values(?,?,?,?)");

psmnt.setString(1, ff.getPath());
psmnt.setString(2, ff.getName());

int s = psmnt.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){
    e.printStackTrace();
}
}
%>

【问题讨论】:

  • 我认为缺少类别和标签的绑定参数
  • 你有什么异常吗?还要在预付账单中绑定类别和标签的参数
  • 尝试将 Servlet 用于业务逻辑。这在 JSP 中不是首选
  • 请编辑我的代码。

标签: mysql jsp


【解决方案1】:

类别和标签不包含任何要插入数据库的值。不需要那些变量。
按照下面的代码:

psmnt = connection.prepareStatement("insert into file_upload(file_path,file_name) values(?,?)");

【讨论】:

    猜你喜欢
    • 2020-01-28
    • 1970-01-01
    • 2017-09-09
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2012-07-25
    • 2013-08-17
    相关资源
    最近更新 更多