图片上传主要代码(学生系统个人信息中)
-
步骤一:在web目录下新建一个项目(图片上传的路径)
-
步骤二:导入commons-fileupload-1.32.jar和commons-io-2.5.jar
-
步骤三:编写jsp页面(add.jsp)
<div class="form-group">
<label for="tel" class="col-sm-2 control-label">照片</label>
<div class="col-sm-5">
<input type="file" name="pic" class="form-control" id="pic" placeholder="照片">
</div>
</div>
- 步骤四:编写servlet(StudentServlet.java)
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
private Map<String, String> getParameterMap(HttpServletRequest req) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
FileUpload fileUpload = new FileUpload(diskFileItemFactory);
Map<String,String> map = new HashMap<>();
try {
List<FileItem> list = fileUpload.parseRequest(req);
for (FileItem fileItem : list) {
if(fileItem.isFormField()){//判断是否是 普通的表单项
map.put(fileItem.getFieldName(),fileItem.getString());
}else{//说明是 文件上传的表单项,处理 上传文件,将上传文件 保存到服务器的硬盘中
//拼接路径
String path = this.getServletContext().getRealPath("/")+"upload"+ File.separator;
String fileName = UUID.randomUUID().toString();
String suffix = fileItem.getName().substring(fileItem.getName().lastIndexOf('.'));
//TODO 验证 大小、类型 等是否符合要求
File file = new File(path+fileName+suffix);
fileItem.write(file);
//将 路径 存储到 map ,以再便存到数据库里
map.put(fileItem.getFieldName(),"/upload/"+fileName+suffix);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}