【Java】圖片上傳__Java

來源:互聯網
上載者:User

圖片上傳功能在Controller層實現的完整方法如下:

方法一:

@RequestMapping("toUploadImage.do")         public String upload(@RequestParam MultipartFile uploadfile,                  HttpServletRequest request, HttpServletResponse response,String tid) {          //擷取輸入的檔案名稱             String fileName = uploadfile.getOriginalFilename();             if (StringUtils.isEmpty(fileName)) {                 System.out.println("未上傳檔案名稱為空白");             }             //擷取路徑             String tempPath = request.getSession().getServletContext().getRealPath("/")                     + "upload\\ysdwanimal";             File dir = new File(tempPath);                      if (!tempPath.endsWith(File.separator)) {                 tempPath = tempPath + File.separator;             }             if (!dir.exists()) {                 dir.mkdirs();             }                        System.out.println(tempPath+fileName);             //檢查是否重複上傳             HmImages hmImage = HmImageService.getEntryById(tid);             if(hmImage == null){              return "uploadfail";             }             //重寫資料庫儲存路徑             String lj=request.getScheme() + "://" + request.getServerName()                  + ":" + request.getServerPort() + "/whzhly/upload/ysdwanimal/"+id+".jpg";             //儲存路徑             ysdwAnimal.setLujing(lj);             ysdwAnimalService.saveOrUpdateYsdwAnimal(ysdwAnimal);             //擷取完整的圖片名             String newFile = tempPath + id+".jpg";                      File file = new File(newFile);             //圖片複製到指定檔案夾中,實現路徑             try {                 FileCopyUtils.copy(uploadfile.getBytes(), file);                                  System.out.println("成功上傳");             } catch (IOException e) {                 e.printStackTrace();                 return "uploadfail";             }              return "uploadsuccess";         }  


方法二:

@RequestMapping("/toUpLoadHmImage.do")public @ResponseBody String toUpLoadHmImage(HttpServletRequest request,HttpServletResponse response,ModelMap model){//擷取到項目名稱String projectName =  request.getContextPath();//得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接存取,保證上傳檔案的安全String savePath =  request.getServletContext().getRealPath("/WEB-INF/primary/images");File file = new File(savePath);//判斷上傳檔案的儲存目錄是否存在if(!file.exists() && !file.isDirectory()){//不存在,則建立目錄file.mkdir();}//訊息提示String message = "";try {DiskFileItemFactory factory = new DiskFileItemFactory();//建立一個檔案上傳解析器ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("utf-8");//設定上傳的檔案總的大小不能超過5M  upload.setSizeMax(1024 * 1024 * 5);//判斷提交上來的資料是否是上傳表單的資料if(!ServletFileUpload.isMultipartContent(request)){return message;}/* * 使用ServletFileUpload解析器解析上傳資料, * 解析結果返回的是一個List<FileItem>集合 */List<FileItem> list = upload.parseRequest(request);for(FileItem item : list){if(item.isFormField()){//如果fileitem中封裝的是普通輸入項的資料String itemName = item.getFieldName();String itemValue = item.getString("utf-8");System.out.println(itemName + "=" + itemValue);}else {//如果fileitem中封裝的是上傳檔案//得到上傳的檔案名稱String fileName =item.getName(); System.out.println("fileName=" + fileName);if(fileName == null || fileName.trim().equals("")){continue;}//處理擷取到的上傳檔案的檔案名稱的路徑部分,只保留檔案名稱部分fileName = fileName.substring(fileName.lastIndexOf("\\")+1);//擷取item中的上傳檔案的輸入資料流InputStream inputStream = item.getInputStream();//建立一個檔案輸出資料流FileOutputStream outputStream = new FileOutputStream(savePath+"\\"+fileName);//建立一個緩衝區byte buffer[] = new byte[1024];//判斷輸入資料流中的資料是否已經讀完的標識int len = 0;//迴圈將輸入資料流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料while((len=inputStream.read(buffer))>0){//使用FileOutputStream輸出資料流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中outputStream.write(buffer, 0, len);}//關閉輸入資料流inputStream.close();//關閉輸出資料流outputStream.close();//刪除處理檔案上傳時產生的臨時檔案item.delete();message = "檔案上傳成功";}}} catch (Exception e) { message= "檔案上傳失敗。"; e.printStackTrace();}return message;}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.