分享一款jsp中利用servlet實現圖片上傳代碼,也算是超級簡單的方法了,有需要的朋友參考一下。 代碼如下 復制代碼
首先,頁面中即JSP中需要如下的組件:
<h2 class="h2">
上傳照片:
</h2>
<form action="pic.do" method="post"
enctype="multipart/form-data">
<input type="file" name="file1" />
<input type="submit" value=" 上傳" />
</form>
而後在servlet中可以通過如下代碼來完成文件的上傳操作:
if(path.equals("/pic")){
//獲得登錄用戶的id,用於創建新的文件夾,存放該用戶上傳的文件s
HttpSession session = request.getSession();
User user=(User)session.getAttribute("user");
long id=user.getId();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
try {
List<FileItem> items = sfu.parseRequest(request);
for(int i =0;i<items.size();i++){
FileItem item =items.get(i);
if(item.isFormField()){
String name = item.getString();
System.out.println("name"+name);
}
else{
ServletContext context = getServletContext();
path =context.getRealPath("upload");
File file = new File(path+"\pic_"+id);
file.mkdir();
String fileName1 = item.getName();
String fileName = fileName1.substring(fileName1.lastIndexOf("\")+1);
file = new File(path+"\"+"pic_"+id+"\"+fileName);
item.write(file);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}