上次利用SpringMVC實現圖片上傳,這個是客戶端將圖片和其餘字段一塊兒上傳而後一塊兒處理的。(有什麼壞處暫時也沒有想到)總之此次的但願可以將圖片存儲的服務獨立出來,暫時用Jersey實現一個接口(老大說按道理應該用WebService來實現,但我在這裏沒以爲二者有什麼不一樣呀=。=),而後在SpringMVC中將圖片提交到Jersey接口,完成存儲。java
這個是獨立出來的圖片存儲項目結構node
config.xml配置文件中只添加了一個絕對路徑和一個虛擬路徑spring
<config> <root>D:\\recommend\\images\\</root> <uriRoot>/static/image/recommendation/</uriRoot></config>
springcontext.xml配置文件中將須要注入的東西配好便可apache
<context:component-scan base-package="com.xxx.upload">
RestFulApplication.java中註冊必要的類json
public RestFulApplication(){ register(RequestContextFilter.class); // Add additional features such as support for Multipart. register(MultiPartFeature.class); //load Resource register(RecommendationPictureResource.class); }
RecommendationPictureResource.javaapp
private final Log logger = LogFactory.getLog(RecommendationPictureResource.class); @Autowired @Qualifier("pictureService") PictureService pictureService;//存儲圖片的服務類 @Autowired @Qualifier("xmlUtils") XMLUtils xmlUtils;//封裝org.apache.commons.configuration.XMLConfiguration的一個xml文件解析工具類,用來讀取config.xml配置文件 @POST @Path("/upload") @Produces("application/json;charset=UTF-8") @Consumes(MediaType.MULTIPART_FORM_DATA) public String loadPic( @FormDataParam("type") String type, @FormDataParam("resourceId") String resourceId, @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader){ ObjectNode result = new ObjectMapper().createObjectNode(); if (type==null || resourceId == null || fileInputStream == null) { result.put("ret_code", 10001); result.put("ret_msg", "Illegal Parameters"); return result.toString(); } String fileName = contentDispositionHeader.getFileName(); String path = type + File.separatorChar + resourceId + File.separatorChar + fileName; //存儲路徑 String dstFilePath = xmlUtils.getString("root") + path; pictureService.saveFile(fileInputStream, dstFilePath); logger.info("success save pic file, dstFilePath = " + dstFilePath); String uriPath = xmlUtils.getString("uriRoot") + path; logger.info("uriPath = " + uriPath); result.put("uriPath", uriPath); return result.toString(); } @POST @Path("/delete") @Produces("application/json;charset=UTF-8") public void deletePic(@FormParam("uriPath") String uriPath){ String uriRoot = xmlUtils.getString("uriRoot"); String path = uriPath.substring(uriRoot.length()); String dstFilePath = xmlUtils.getString("root") + path; pictureService.deleteFile(dstFilePath); }
PictureService.java接口ide
public void saveFile(InputStream fileInputStream, String dstFilePath); public void deleteFile(String dstFilePath);
PictureServiceImpl.java實現類工具
private final Log logger = LogFactory.getLog(PictureServiceImpl.class); @Override public void saveFile(InputStream fileInputStream, String dstFilePath) { OutputStream outputStream = null; try { File file = new File(dstFilePath); if(!file.exists()){ if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } outputStream = new FileOutputStream(new File( dstFilePath)); int read = 0; byte[] bytes = new byte[1024]; outputStream = new FileOutputStream(new File(dstFilePath)); while ((read = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } }else{ logger.info("the pic already exist."); } } catch (IOException e) { logger.error(e); e.printStackTrace(); }finally{ try { fileInputStream.close(); outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.error("close stream defeat"); e.printStackTrace(); } } } @Override public void deleteFile(String dstFilePath) { File file = new File(dstFilePath); file.delete(); file.getParentFile().delete(); }
刪除這兒還有問題,就是利用上述Jersey接口上傳好的圖片一直被JVM佔用,致使沒法刪除,但我如今仍然看不破哪兒的資源沒有釋放~~post
對應的SpringMVC中經過調用上述Jersey接口的部分代碼ui
try { String upload_host = "localhost:8080"; String pic_upload_uri = "http://" + upload_host + "/xxx/upload"; MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();//org.apache.http.entity.mime.MultipartEntityBuilder //type和contentId在上述接口中用來生成存儲路徑 entityBuilder.addTextBody("type", type); entityBuilder.addTextBody("resourceId", contentId); ContentType contentType = ContentType.parse(poster.getContentType()); String fileName = poster.getOriginalFilename(); entityBuilder.addBinaryBody("file", poster.getInputStream(), contentType, fileName); HttpClient client = new HttpClient();//本身封裝好的Http工具類 String loadResult = client.post(pic_upload_uri, entityBuilder.build());//上傳成功的話返回json格式字符串,其中包含一個uriPath //利用Jackson解析返回結果 JsonNode node = new ObjectMapper().readTree(loadResult); uriPath = node.get("uriPath").asText(); logger.info("load pic success! uriPath = " + uriPath); } catch (Exception e) { logger.error("load pic error ! reason:" + e.getMessage()); }
以上,實現圖片上傳服務,基本與業務無關,但調用的方式仍是不太好,url路徑很差配置,直接寫在了代碼中,還須要改。