前些天在使用七牛云存储进行数据上传的过程中,发现七牛提供的SDK仅支持以File的形式进行上传,不支持以InputStream的形式进行上传,特对其进行了相应的扩展,具体扩展如下:
import java.io.InputStream; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import com.qiniu.api.config.Config; import com.qiniu.api.io.PutExtra; import com.qiniu.api.io.PutRet; import com.qiniu.api.net.CallRet; import com.qiniu.api.net.Client; public class QiNiuIoApi { public static final String UNDEFINED_KEY = "?"; public static final int NO_CRC32 = 0; public static final int AUTO_CRC32 = 1; public static final int WITH_CRC32 = 2; public static PutRet put(String uptoken, String key, InputStream input, PutExtra extra) { if (input == null) { return new PutRet(new CallRet(400, new Exception("InputStream can not be null."))); } if (key == null) { key = UNDEFINED_KEY; } MultipartEntity requestEntity = new MultipartEntity(); try { requestEntity.addPart("token", new StringBody(uptoken)); InputStreamBody fileBody = new InputStreamBody(input, key); requestEntity.addPart("file", fileBody); requestEntity.addPart("key", new StringBody(key)); if (extra.checkCrc != NO_CRC32) { if (extra.crc32 == 0) { return new PutRet(new CallRet(400, new Exception("no crc32 specified!"))); } requestEntity.addPart("crc32", new StringBody(extra.crc32 + "")); } } catch (Exception e) { e.printStackTrace(); return new PutRet(new CallRet(400, e)); } String url = Config.UP_HOST; CallRet ret = new Client().callWithMultiPart(url, requestEntity); return new PutRet(ret); } }
时间: 2024-11-08 23:27:33