檔案存到本地---SSM配置Ueditor實現圖片的上傳
阿新 • • 發佈:2019-02-20
一般我們實現的圖片自定義上傳是將圖片是上傳到tomcat的目錄之下,這樣會出現一個問題,當你重新部署你的工程的時候,tomcat會將你的圖片全部都清空,那麼這樣你將圖片存到資料庫當中將會變的毫無意義!接下來實現如何將圖片存取在非tomcat的目錄之下!!!
1.修改檔案輸出的位置
- @Controller
- public class ImageController {
- @Autowired
- private ImageService imageService;
-
@RequestMapping(value="/uploadImage",method =
- @ResponseBody
- public Map<String,Object> uploadFile(@RequestParam(value = "upfile", required = false) MultipartFile file,
- HttpServletRequest request,HttpServletResponse response){
-
Map<
- String realName = null;
- String uuidName = null;
- String realPath = null;
- try {
- Image image = new Image();
- //檔案原來的名稱
-
realName = getRealName(file.getOriginalFilename());
- //得到這個檔案的uuidname
- uuidName = this.getUUIDFileName(file.getOriginalFilename());
- //圖片儲存的工程
- // realPath = request.getServletContext().getRealPath("/images");
- //真實路徑
- // String roolPath = request.getSession().getServletContext().getRealPath("/");
- //這裡測試的是 把圖片不存在 釋出目錄下
- realPath = "F:\\schoolproject\\images";
- image.setName(realName);
- image.setUrl(realPath);
- image.setUuidname(uuidName);
- //得到檔案的輸入流
- InputStream in = new BufferedInputStream(file.getInputStream());
- OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(realPath,uuidName)));
- IOUtils.copy(in, out);
- in.close();
- out.close();
- int flag = imageService.insertImage(image);
- if(flag!=0){
- map.put("state", "SUCCESS");// UEDITOR的規則:不為SUCCESS則顯示state的內容
- map.put("url","/images/"+uuidName); //能訪問到你現在圖片的路徑 這裡
- map.put("title","");
- map.put("original","realName" );
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- map.put("state", "檔案上傳失敗!"); //在此處寫上錯誤提示資訊,這樣當錯誤的時候就會顯示此資訊
- map.put("url","");
- map.put("title", "");
- map.put("original", "");
- e.printStackTrace();
- }
- return map;
- }
- private String getExtName(String s, char split) {
- int i = s.lastIndexOf(split);
- int leg = s.length();
- return i > 0 ? (i + 1) == leg ? " " : s.substring(i+1, s.length()) : " ";
- }
- private String getUUIDFileName(String fileName){
- UUID uuid = UUID.randomUUID();
- StringBuilder sb = new StringBuilder(100);
- sb.append(uuid.toString()).append(".").append(this.getExtName(fileName, '.'));
- return sb.toString();
- }
- private String getRealName(String originalName){
- //System.out.println(originalName.contains("."));
- if(originalName.contains(".")){
- String [] as = originalName.split("\\.");
- //System.out.println(as[0]);
- return as[0];
- }else {
- return originalName;
- }
- }
- }
2.修改server.xml檔案
到你的eclipse工作目錄中找到server.xml檔案,我的server.xml檔案所在的目錄如下:
F:\schoolproject\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\conf,在<Host></Host>標籤中新增下面的一句話
- <ContextdocBase="F:\schoolproject\images"path="/SpringMVCDemo/images"reloadable="false"/>
這樣就能訪問到你非tomcat目錄下的檔案了!!!它這裡做了個對映而已!
原文連結:http://blog.csdn.net/qq_34292044/article/details/72453119