首页 > 代码库 > jersey上传图片
jersey上传图片
本文来自于我的个人博客:jersey上传图片
今天刚好要做一个用户上传图片的功能,但是需要通过restful api上传,于是通过查询资料以及不断尝试,终于走出了这个图片上传一直报错的困扰,现在将详细代码贴上,希望对后来者有帮助:
客户端:
依赖包:
jersey-client
jersey-multipart
源码:
package com.speakword.client; import java.io.File; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.speakword.entity.OutputMessage; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.multipart.FormDataMultiPart; import com.sun.jersey.multipart.file.FileDataBodyPart; public class FileManageApiClient { private static Logger log = Logger.getLogger(FileManageApiClient.class); private static String url = ""; private static final String uploadUserPic = "/upload/uploadUserPic"; private static Client client; public static void init(String path) { url = path; client = Client.create(); client.setConnectTimeout(5000); client.setReadTimeout(5000); } public static OutputMessage uploadUserPic(String file, Long userid, String suffix) { String picPath = url + uploadUserPic+"?userid=" +userid; WebResource r = client.resource(picPath); try { File f = new File(file); //构建一个form data体 FileDataBodyPart fdp = new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE); FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); formDataMultiPart.bodyPart(fdp); ClientResponse response = r.type(MediaType.MULTIPART_FORM_DATA) .post(ClientResponse.class, formDataMultiPart); String result = response.getEntity(String.class); if(null != result && !"".equals(result) && response.getStatus() == 200) { Gson gson = new Gson(); OutputMessage om = gson.fromJson(result, OutputMessage.class); return om; } else { log.error("上传图片出错..."+file+" " + userid + ", " + result); } } catch(Exception e) { log.error("上传图片失败",e); } return null; } }
服务端:
依赖包:
jersey-core
jersey-server
jersey-multipart
mimepull
jersey resource代码:
package com.sns.resource; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import org.apache.log4j.Logger; import com.google.gson.JsonObject; import com.sns.business.service.UploadImageService; import com.sun.jersey.multipart.FormDataBodyPart; import com.sun.jersey.multipart.FormDataMultiPart; /** * 图片上传 * @author lifeix * */ @Path("/upload") public class UploadImageResource { private static Logger log = Logger.getLogger(UploadImageResource.class); @POST @Path("/uploadUserPic") @Consumes(MediaType.MULTIPART_FORM_DATA) // 消费注解必须是这个类型 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public String uploadImg(FormDataMultiPart form, @Context UriInfo uri, @Context HttpServletRequest request){ JsonObject json = new JsonObject(); String suffix = "png"; if(form == null) { json.addProperty("msg", "参数错误"); json.addProperty("code", 304); return json.toString(); } FormDataBodyPart part = form.getField("file"); InputStream is = part.getValueAs(InputStream.class); try { if(is.available() == 0) { json.addProperty("msg", "数据流为0"); json.addProperty("code", 304); return json.toString(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } MultivaluedMap<String, String> mm = uri.getQueryParameters(); Long userid = Long.parseLong(mm.getFirst("userid")); return UploadImageService.uploadUserPic(is, userid, request, suffix); } }
上传文件处理类:
package com.sns.business.service; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.google.gson.JsonObject; public class UploadImageService { private static Logger log = Logger.getLogger(UploadImageService.class); private static final String uploadPath = "image/bigger/%s/server/upload/%s/%s"; //1.来源 2.时间 3.pic /** * 上传用户头像 * @param is * @param userid * @param request * @param suffix * @return */ public static String uploadUserPic(InputStream is, Long userid, HttpServletRequest request, String suffix) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); String time = sdf.format(new Date()); String us = "pic"; String path = uploadPath; path = String.format(path, "ts",time,us); String newPath = "d:/blogphoto/" + path; File file = new File(newPath); if(!file.exists()) { file.mkdirs(); } String fileName = System.currentTimeMillis()+"u"+userid+"." + suffix; newPath = newPath + "/" + fileName; file = new File(newPath); JsonObject json = new JsonObject(); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { log.error("创建上传文件出错---" + path+"/"+fileName,e); json.addProperty("msg", "上传文件失败"); json.addProperty("code", 500); return json.toString(); } } FileOutputStream fos = null; try { fos = new FileOutputStream(file,true); } catch (FileNotFoundException e) { log.error("构建输出流出错---" + path,e); json.addProperty("msg", "上传文件失败"); json.addProperty("code", 500); return json.toString(); } FileChannel fc = null; try { fc = fos.getChannel(); } catch(Exception e) { log.error("获取文件通道出错---" + path,e); json.addProperty("msg", "上传文件失败"); json.addProperty("code", 500); return json.toString(); } //使用java nio上传图片 ByteBuffer buffer = null; try { buffer = ByteBuffer.allocateDirect(is.available()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } byte[] bb = null; try { bb = new byte[is.available()]; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { while(is.read(bb) > 0) { buffer.put(bb); buffer.flip(); fc.write(buffer); buffer.clear(); } json.addProperty("msg", "上传成功"); json.addProperty("code",200); json.addProperty("filePath", path+"/"+fileName); } catch (IOException e) { log.error("写入文件出错---" + path +"/"+fileName,e); json.addProperty("msg", "上传文件失败"); json.addProperty("code", 500); } finally { if(fc != null) { try { fc.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(null != is) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Gson gson = new Gson(); String str = gson.toJson(json); return str; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。