ajax上傳帶檔案的form表單,springmvc接收
阿新 • • 發佈:2019-02-03
資料都儲存到HttpServletRequest中
@Override public boolean insertBook(HttpServletRequest request) { try{ //用於封裝資料 Book book = new Book(); //解析請求中的資料 MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request; String bookName = mpRequest.getParameter("bookName"); float price = Float.parseFloat(mpRequest.getParameter("price")); Integer num = Integer.parseInt(mpRequest.getParameter("num")); String date = mpRequest.getParameter("publishDate"); SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd"); Date publishDate = format.parse(date); //封裝資料 book.setBookName(bookName); book.setPrice(price); book.setNum(num); book.setPopular(0); book.setPublishDate(publishDate); MultipartFile file = mpRequest.getFile("imageUrl"); String path = request.getSession().getServletContext().getRealPath("bookImage"); String imageUrl = UploadUtil.uploadFile(file, path); book.setImageUrl(imageUrl); bookMapper.insertBook(book); return true; }catch(Exception e){ e.printStackTrace(); return false; } //return false; }
解析存放圖片的imageUrl
public static String uploadFile(MultipartFile file, String path) throws IOException{ //上傳檔案的真實名稱 String name = file.getOriginalFilename(); //System.out.println(name); //獲取字尾名 String suffixName = name.substring(name.lastIndexOf(".")); //System.out.println(suffixName); //自定義隨機數 String hash = Integer.toHexString(new Random().nextInt()); String fileName = hash + suffixName; //System.out.println(fileName); File tempFile = new File(path, fileName); if(!tempFile.getParentFile().exists()){ tempFile.getParentFile().mkdir(); } if(tempFile.exists()){ tempFile.delete(); } tempFile.createNewFile(); file.transferTo(tempFile); return tempFile.getName(); }
參考文章:http://blog.csdn.net/wlphyl/article/details/51571402