您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用java實現(xiàn)文件上傳、下載、圖片預(yù)覽功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
多文件保存到本地:
@ResponseBody @RequestMapping(value = "/uploadApp",produces = { "application/json;charset=UTF-8" },method= RequestMethod.POST) public String uploadApp( HttpServletRequest request,@RequestParam("file") MultipartFile[] file) throws IOException { try { if(file.length > 0) { String name = file[0].getOriginalFilename().split(";")[0]; String fileUrlName = CommonEnum.FILEPATH+"/"+name; for (int i = 0; i < file.length; i++) { FileUtils.copyInputStreamToFile(file[i].getInputStream(), new File(fileUrlName, file[i].getOriginalFilename().split(";")[1])); } return "success"; }else{ return "null"; } }catch (Exception e){ e.printStackTrace(); return "error"; } }
下載文件:
@RequestMapping(value = "/download", method = RequestMethod.GET) @ResponseBody public void download(@RequestParam Map<String, Object> data, HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException { String time = DateUtil.formatFromDate("yyyyMMddHHmmss", new Date()); List<Map<String, Object>> urllist = companyService.findByIMG(data); String path = (String) urllist.get(0).get("imgurl"); String docx = StringUtils.substringAfterLast(path, "."); String fileName = time+"."+docx; // 文件的默認(rèn)保存名 InputStream inStream = new FileInputStream(path);// 文件的存放路徑 response.reset(); response.setContentType("bin"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); byte[] b = new byte[100]; int len; try { while ((len = inStream.read(b)) > 0) response.getOutputStream().write(b, 0, len); inStream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 讀取圖片 */ @RequestMapping(value = "/iomoreimgcom", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.GET) @ResponseBody public synchronized void iomoreimgcom(HttpServletRequest request, HttpServletResponse response) throws Exception { String url = request.getParameter("url"); File file = new File(url); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); response.setHeader("Content-Type", "image/jpeg"); byte b[] = new byte[1024]; int read; try { while ((read = bis.read(b)) != -1) { bos.write(b, 0, read); } //request.getRequestDispatcher("/components/hazard/yscchird.html").forward(request, response); } catch (Exception e) { // TODO: handle exception } finally { if (bos != null) { bos.close(); } if (bis != null) { bis.close(); } } }
前端請求直接拼接圖片路徑即可。
以上是“如何使用java實現(xiàn)文件上傳、下載、圖片預(yù)覽功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。