Java 上传图像并保存在 JSP 中的 Web 内容文件夹中并在数据库中保存图像路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20850973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload image and Save inside Web Content Folder in JSP and Save Image Path in Database
提问by Purple Owl
My goal is to upload an image and save inside images folder to Web Content Folder.
我的目标是上传图像并将内部图像文件夹保存到 Web 内容文件夹。
{Please see the image below}
{请看下图}
and save the image path into database
并将图像路径保存到数据库中
{Please see the image below}
{请看下图}
I encountered some problem at this linkI tried to do but I did not managed to save the image to images/users folder.
我在 尝试执行此链接时遇到了一些问题,但我没有设法将图像保存到图像/用户文件夹。
And I realize that the save path is store at my C DRIVE. What if I change my computer? Will the image will be there?
我意识到保存路径存储在我的 C 驱动器中。如果我换了电脑怎么办?图像会在那里吗?
Below are my codes. Help will be appreciate.. Thanks! :)
下面是我的代码。帮助将不胜感激..谢谢!:)
In jsp
在jsp中
<input type="file" name="file">
In servlet
在servlet 中
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 "";
}
回答by Sureshkumar Panneerselvan
Follow the link provided by SasiKathimanda for code implementation.
按照 SasiKathimanda 提供的链接进行代码实现。
Create the file name as 'OrignalFilename+SystemTimeInMills' in order to avoid overriding already uploaded file with same filename.
将文件名创建为“OrignalFilename+SystemTimeInMills”,以避免覆盖已上传的具有相同文件名的文件。
Otherwise check for duplicate filename before write filecontent to server.
否则在将文件内容写入服务器之前检查重复的文件名。
Follow the pattern(For DB File Path) if you need to provide download option(later), otherwise you can save the uploaded absolute file path.
如果您需要提供下载选项(稍后),请遵循模式(对于数据库文件路径),否则您可以保存上传的绝对文件路径。