我的jsp页面中有一个表单,其中有一个文本输入和一个文件输入。
<form action="servlet/FileUploadHandler" method="post" class="post" id="profilepost" enctype="multipart/form-data">
<div class="form-group">
<label for="createPost">Photo</label>
<input type="text" name="url" class="form-control" id="inputcomment" placeholder="URL...">
</div>
<div class="form-group">
<label for="exampleInputFile">Upload photo</label>
<input type="file" name="file" id="exampleInputFile">
<button type="submit" class="btn btn-primary">Post</button>
</form>
我使用的servlet如下:
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadHandler extends HttpServlet {
private final String UPLOAD_DIRECTORY = "C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\ismgroup9\\fileUpload";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
request.setAttribute("photoname", name);
}
}
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message", "Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/uploadfileController.jsp").forward(request, response);
}
}
但这仅适用于照片。我能做什么才能同时拥有文字和照片?我想将它们插入我的mysql数据库中的同一个表中。
答案 0 :(得分:0)
试试这个,也许它会帮助你解决问题。
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
request.setAttribute("photoname", name);
}else{
// here get value of other parameter which is not file type
System.out.println(item.getFieldName()+" = "+item.getString());
}
}