我想上传图片以及来自jsp表单的数据。然后将这些值发送到servlet。 我的jsp表单代码如下:
<form action="AddController" method="post" name="addform" id="addform" >
Name : <input type="text" name="myname">
Image : <input type="file" accept="image/*" name="file">
<input type="submit" name="add" id="add" value="Save"/>
</form>
servlet的代码如下。代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String add=request.getParameter("add");
if(add!=null) {
String name =request.getParameter("myname");
System.out.println(myname);
String SAVE_DIR = "C:/uploadFiles";
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = SAVE_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}
request.setAttribute("message", "Upload has been done successfully!");
getServletContext().getRequestDispatcher("/addsuccessful.jsp").forward(
request, response);
}
}
/**
* Extracts file name from HTTP header content-disposition
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
我从文本框中获取名称值。但图片未上传。 当我添加enctype =&#34; multipart / form-data&#34;在形式上,我没有得到名称价值。 如何解决这个问题????