java web 存进数据库中的图片名和硬盘中的图片名为和不同??

CyanQueen 发布于 2014/04/23 21:58
阅读 455
收藏 1

存进数据库中的图片名和硬盘中的图片名为和不同??

详细如下:

数据库中:


上传到的文件中:

上传代码具体如下:

private Book uploadBook(HttpServletResponse response,HttpServletRequest request) {

                 Book book = new Book();

                

                 FileItemFactory factory = new DiskFileItemFactory();

                 ServletFileUpload upload = new ServletFileUpload(factory);

 

                 if (!upload.isMultipartContent(request)) {

                          return null;

                 }

                 try {

                          List<FileItem> items = upload.parseRequest(request);

                          for (FileItem fileItem : items) {

                                   if (fileItem.isFormField()) {

                                            String name = fileItem.getFieldName();

                                            String value = fileItem.getString("UTF-8");

                                            BeanUtils.copyProperty(book, name, value);

                                   } else {

                                            String fileName = fileItem.getName();

                                           

 

                                            String realPath = this.getServletContext().getRealPath("/images");

 

                                            InputStream is = fileItem.getInputStream();

                                            FileOutputStream fos = new FileOutputStream(realPath + "\\" + makeFileName(fileName));

 

                                            byte[] buffer = new byte[1024];

                                            int len = 0;

                                            while ((len = is.read(buffer)) > 0) {

                                                    fos.write(buffer, 0, len);

                                            }

                                            is.close();

                                            fos.close();

                                            fileItem.delete();

                                            book.setImage(makeFileName(fileName));

                                   }

 

                          }

                         

                         

                 } catch (Exception e) {

                          e.printStackTrace();

                 }

                

                 return book;

         }

 

         private String makeFileName(String fileName) {

                 String ext = fileName.substring(fileName.lastIndexOf(".")+1);

                 return UUID.randomUUID().toString() +"."+ ext;

         }

最后在jsp里面${pageContext.request.contextPath}/images/${book.image}的时候抛404错误,说没找到,,,,求大神普度啊,,

 

加载中
0
McZen
McZen

两次makeFileName,但是 UUID.randomUUID().toString()会返回不同的吧

CyanQueen
CyanQueen
原来是这么回事啊,谢谢!!
0
JacCoffee
JacCoffee

楼上+1,楼主自己去看UUID的生成策略吧

0
忧郁麦芽
忧郁麦芽

...看到random~你还在纠结吗0 0!

返回顶部
顶部