上传到本地服务器的文件。如何使用jsp将文件路径和文件名保存到mysql数据库中?

时间:2017-04-17 05:04:40

标签: mysql jsp

我曾尝试将文件上传到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();
}
}
%>

1 个答案:

答案 0 :(得分:0)

类别和标签不包含要插入数据库的任何值。变量没有必要   请遵循以下代码:

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