1. 程式人生 > >圖片上傳返回上傳連結

圖片上傳返回上傳連結

@Value(("#{prop.uploadHost}"))private String uploadHost;@RequestMapping(value = "/insertImgUrl")public ResultData insertImgUrl(HttpServletRequest request, HttpServletResponse response){    response.setContentType("application/json");    String rootPath = request.getSession().getServletContext().getRealPath("/"
); MultipartHttpServletRequest Murequest =(MultipartHttpServletRequest)request; Map<String, MultipartFile> files = Murequest.getFileMap();//得到檔案map物件 // 例項化一個jersey Client client = new Client(); for(MultipartFile pic: files.values()){ String originalFilename = pic.getOriginalFilename(); //原來的檔名
//String uploadInfo = Upload.upload(client, pic, request, response, uploadHost, ueditor); String[] txt1 = originalFilename.split("\\."); String txt = txt1[txt1.length - 1]; if (StringUtils.isBlank(originalFilename)) { continue; } File tempFile = new File(ueditor
, originalFilename); Long ss = System.currentTimeMillis(); File newfile = new File(tempFile.getParent() + File.separator + ss + "." + txt); tempFile.renameTo(newfile); if (tempFile.exists()) { //newfile = new File(tempFile.getParent() + File.separator + ss+"."+txt); tempFile.renameTo(newfile); } if (!newfile.exists()) { newfile.getParentFile().mkdirs(); try { newfile.createNewFile(); pic.transferTo(newfile); //ImageUtil imageUtil = new ImageUtil(); Integer isUpload=0; SftpUtil sftpUtil=new SftpUtil(); isUpload=sftpUtil.LunboUpload(ss + "." + txt, ss); if(isUpload==0) { return ResultData.returnResultData(ResultData.DATA_FALSE,"上傳失敗"); } } catch (Exception e) { e.printStackTrace(); } } String uploadInfo=uploadHost+ss+"."+txt; if(!"".equals(uploadInfo)) { return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",uploadInfo); } else { return ResultData.returnResultData(ResultData.DATA_FALSE,"false","上傳失敗"); } } return ResultData.returnResultData(ResultData.DATA_FALSE,"false","上傳失敗");}
public  synchronized Integer  LunboUpload(String fileName,Long s){    ChannelSftp sftp=null;    try {    SftpUtil sf = new SftpUtil();    String host = ip;    int port = 22;    String username = root;    String password = Password;    //String directory = "/data/sftp/mysftp/lunbo/";    //String uploadFile = "/home/ftp/img/"+fileName; String uploadFile = "G:/ceshi/image/"+fileName;    sftp=sf.connect(host, port, username, password);    sf.upload(directory, uploadFile, sftp);    sftp.getSession().disconnect();    sftp.quit();    sftp.disconnect();//關閉    //sf.download(directory, downloadFile, saveFile, sftp);    //sf.delete(directory, deleteFile, sftp); return 1;    } catch (Exception e) {        //sftp.getSession().disconnect(); sftp.quit();        sftp.disconnect();//關閉 return 0;    }}
要注意圖片伺服器使用ftp傳輸,同時要注意關閉ftp連結,保證最終的圖片正常傳輸,
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <property name="defaultEncoding" value="UTF-8"/></bean>