我想将图像名称添加到我的数据库,将图像添加到文件夹,但我不知道我做错了什么,数据库上传和表格的编码如下:
<form method="get" enctype="multipart/form-data" action="imgUpload.jsp">
<input type="file" name="image">
<input type="submit" >
</form>
和jsp编码:
try{
String ImageFile="";
String itemName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart){
}
else{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try{
items = upload.parseRequest(request);
}
catch (FileUploadException e){
e.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext()){
FileItem item = (FileItem) itr.next();
if (item.isFormField()){
String name = item.getFieldName();
String value = item.getString();
if(name.equals("image")){
ImageFile=value;
}
}
else{
try{
itemName = item.getName();
File savedFile = new File(config.getServletContext().getRealPath("/")+"\\img\\gamePoster\\"+itemName);
item.write(savedFile);
}
catch (Exception e){
out.println("Error"+e.getMessage());
}
}
}
try{
String str="insert into test (img_name) values ('"+itemName+"')";
Statement stmt=con.createStatement();
int rs=stmt.executeUpdate(str);
}
catch(Exception el){
out.println("Inserting error"+el.getMessage());
}
}
}
catch (Exception e){
out.println(e.getMessage());
}
答案 0 :(得分:0)
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE); // sets maximum size of request (include file + form data)
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println("item.getFieldName() => "+item.getFieldName());
String fileAttr[] = fileName.split("\\.");
String newFileName = fileAttr[0];
int i = 1;
while (true) {
File f = new File(uploadPath + "\\" + newFileName + "." + fileAttr[1]);
if (f.exists()) {
newFileName = fileAttr[0] + i;
i++;
} else {
fileName = newFileName + "." + fileAttr[1];
break;
}
}
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
request.setAttribute("message","Upload has been done successfully!");
} else {
System.out.println("1 item.getFieldName() => "+item.getFieldName());
if("description1".equalsIgnoreCase(item.getFieldName())){
//this part is for other field except file field
}
}
}
}
你必须添加commons-fileupload-1.3.jar
答案 1 :(得分:-2)
在表单标记中尝试此代码
<form enctype="multipart/form-data" action="imgins.jsp?id=<%=id%>" method="post">
<b><font color="white">Choose the file To Upload: </font> </b>
<input type="file" name="file">
<input type="submit" name="submit" value="submit">
</form>
然后您可以使用以下代码将图像插入数据库
<%
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(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost/movie";
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
File f = new File(saveFile);
int id = Integer.parseInt(request.getParameter("id").toString());
psmnt = connection.prepareStatement("update movie set image=? where movie_id=?");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream) fis, (int) (f.length()));
psmnt.setInt(2, id);
out.println("hi");
int s = psmnt.executeUpdate();
if (s > 0) {
System.out.println("Uploaded successfully !");
response.sendRedirect("home.jsp");
} else {
System.out.println("Error!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
%>