jersey上传图片,图片上传
热度
3
评论 76
www.BkJia.Com 网友分享于:
2014-08-14 08:08:54 浏览数29202次
id="cproIframe_u1983349_4" width="250" height="250" src="http://pos.baidu.com/acom?adn=3&at=231&aurl=&cad=1&ccd=24&cec=UTF-8&cfv=17&ch=0&col=zh-CN&conBW=0&conOP=1&cpa=1&dai=4&dis=0<r=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DpbhtJEC5SE4Oyg5l4KB9LABMzmeLbXJJFYjpz2FwyP2gzoUyrYLPrzwQdjIp7heI%26wd%3D%26eqid%3D934dc9ed0002c4320000000555837cb8<u=http%3A%2F%2Fwww.bkjia.com%2FASPjc%2F863455.html&lu_161=0&lunum=6&n=35088068_cpr&pcs=1440x799&pis=10000x10000&ps=544x246&psr=1440x900&pss=1440x574&qn=54283811e4af86a8&rad=&rsi0=250&rsi1=250&rsi5=4&rss0=%23FFFFFF&rss1=%23FFFFFF&rss2=%230000ff&rss3=%23444444&rss4=%23008000&rss5=&rss6=%23e10900&rss7=&scale=&skin=tabcloud_skin_3&stid=5&td_id=1983349&titFF=%E5%AE%8B%E4%BD%93&titFS=12&titTA=left&tn=text_default_250_250&tpr=1434680506581&ts=1&version=2.0&xuanting=0&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=u1983349&ti=jersey%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%EF%BC%8C%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0_WEB%E7%BC%96%E7%A8%8B%E6%95%99%E7%A8%8B%20%7C%20%E5%B8%AE%E5%AE%A2%E4%B9%8B%E5%AE%B6&tt=1434680506566.453.625.626" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true">
id="cproIframe_u1044360_5" width="300" height="250" src="http://pos.baidu.com/acom?adn=3&at=231&aurl=&cad=1&ccd=24&cec=UTF-8&cfv=17&ch=0&col=zh-CN&conBW=0&conOP=1&cpa=1&dai=5&dis=0<r=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DpbhtJEC5SE4Oyg5l4KB9LABMzmeLbXJJFYjpz2FwyP2gzoUyrYLPrzwQdjIp7heI%26wd%3D%26eqid%3D934dc9ed0002c4320000000555837cb8<u=http%3A%2F%2Fwww.bkjia.com%2FASPjc%2F863455.html&lu_161=6&lunum=6&n=35088068_cpr&pcs=1423x799&pis=10000x10000&ps=544x505&psr=1440x900&pss=1423x810&qn=86ff9e2f0fa79cfb&rad=&rsi0=300&rsi1=250&rsi5=4&rss0=%23FFFFFF&rss1=%23FFFFFF&rss2=%230000ff&rss3=%23444444&rss4=%23008000&rss5=&rss6=%23e10900&rss7=&scale=&skin=tabcloud_skin_3&stid=5&td_id=1044360&titFF=%E5%AE%8B%E4%BD%93&titFS=12&titTA=left&tn=text_default_300_250&tpr=1434680506581&ts=1&version=2.0&xuanting=0&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=u1044360&ti=jersey%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%EF%BC%8C%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0_WEB%E7%BC%96%E7%A8%8B%E6%95%99%E7%A8%8B%20%7C%20%E5%B8%AE%E5%AE%A2%E4%B9%8B%E5%AE%B6&tt=1434680506566.642.750.750" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true">
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;
}
}
本文详细介绍了如何利用Jersey客户端和服务器端实现RESTful API中的用户图片上传功能,包括客户端依赖配置、代码实现及服务端处理逻辑。提供了完整的代码示例,旨在帮助后来者解决图片上传过程中遇到的问题。
670

被折叠的 条评论
为什么被折叠?



