我的目标是上传图像并将图像文件夹内保存到 Web 内容文件夹。
{请看下图}
并将图像路径保存到数据库中
{请看下图}
我在尝试做的这个链接上遇到了一些问题, 但我没有设法将图像保存到图像/用户文件夹。
我意识到保存路径存储在我的 C 驱动器中。如果我换电脑怎么办?图像会在那里吗?
以下是我的代码。帮助将不胜感激.. 谢谢!:)
在jsp中
<input type="file" name="file">
在小服务程序中
public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SAVE_DIR = "WebContent\\images\\users";
.........
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + 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);
}
System.out.println(savePath);
}
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 "";
}