我使用jsp和servlet上传图像。我正在使用enctype = multipart / form-data。但我无法将输入字段值提取到servlet中。
这是我的jsp代码
<form method="post" action="uploadImage" enctype="multipart/form-data">
<p>Select file to upload:</p>
<input type="file" name="file" >
<input type="text" name="name" >
<br><br>
<input type="submit" value="Upload" >
</form>
这是我的sevlet代码
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
HttpSession sess=request.getSession();
PrintWriter out = response.getWriter();
int i=0;
String u_id=(String) sess.getAttribute("uid");
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;
}
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
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;
File ff = new File("D:/images/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
try{
Connection con;
PreparedStatement ps,ps1;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dfmc","root","93Pb3gaNv0");
String sql="insert into profilepic_table(uid, image_name) values('"+u_id+"','"+ff.getName()+"')";
ps=con.prepareStatement(sql);
ps.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}
}
此外,我想选择多个文件并上传。
答案 0 :(得分:0)
在定义Servlet之前添加以下代码行,以处理必须使用Multipart注释的multipart/form-data
提交
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
public class ServletName extends HttpServlet { ... }
另外,导入javax.servlet.annotation.MultipartConfig;