看网上的回答说后台直接private File pic;加上get,set就可以得到file,
但是我得到的是String类型的图片名,请问后台如何得到前台选择的file图片
你是想获得上传的图片么?那应该在上传图片的函数里就能拿到你上传图片的路径,就可以找到了。
一开始还以为你要它的type属性呢,,,,,
我并没有单独写一个选择照片的方法,而是在jsp中使用,然后submit提交到后台,现在想的是在后台获取到file,或者是路径,
找到图片转成byte,插入到blob字段当中,但是不知道后台应该如何写(我是新手可能没有完全理解你的意思)
参考:
https://q.cnblogs.com/q/28119/
https://zhidao.baidu.com/question/569710754.html?qbl=relate_question_0&word=jsp%D6%D0%CA%B9%D3%C3%3Cinput%20type%3D%22file%22%20name%3D%22pic%22/%3E
像这样的,uploadFileItem就是图片实体,通过uploadFileItem.getInputStream()获取文件流,in.read转成byte。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//log.debug("------上传文件-----");
CommonUtil.print("------上传文件-----");
FileItem uploadFileItem = null;
request.setCharacterEncoding("UTF-8");
try {
DiskFileItemFactory diskFactory = new DiskFileItemFactory();
diskFactory.setSizeThreshold(1024 * 1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(diskFactory);
upload.setSizeMax(1024 * 1024 * 1024);
List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));
Map<String, Object> params = new HashMap<String, Object>();
for (Iterator<FileItem> iterator = fileItems.iterator(); iterator.hasNext();) {
FileItem fileItem = iterator.next();
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString();
params.put(name, parserStr(value));
//System.out.println(name + " = " + value);
} else {
uploadFileItem = fileItem;
}
}
String name = (String) params.get("shareId");
String picId = CommonUtil.getUUID();
String fileName = picId+"."
+this.getFileType(uploadFileItem.getName());
String savePath = this.getServletContext().getRealPath("/share/images")+File.separator;
//log.info("size:"+uploadFileItem.getSize());
CommonUtil.print("size:"+uploadFileItem.getSize());
String filepath = savePath+fileName;
InputStream in = uploadFileItem.getInputStream();
FileOutputStream out = new FileOutputStream(filepath);
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
CommonUtil.print("---" +uploadFileItem.getName()+
"---上传文件成功-----");
if(null != name ){
Pic obj = new Pic(picId, filepath, name, this.getFileType(uploadFileItem.getName()));
obj.setCurrentDate(new Date());
ActionDao.getInstance().save(obj);
CommonUtil.print("------已写入到数据库中---");
}
this.write(request, response, filepath, "", true);
} catch (Exception e) {
e.printStackTrace();
}
}
你可以用form进行提交后台 不过form 要加 enctype="multipart/form-data"