Skip to content

Instantly share code, notes, and snippets.

@beilly beilly/ShareWX.java
Created Apr 13, 2017

Embed
What would you like to do?
分享文件到微信
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXFileObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
/**
* Created by shibenli on 2017/4/6.
*/
public class ShareWX {
public static void ShareFileToWeiXin(String filePath, String title) {
WXFileObject fileObj = new WXFileObject();
fileObj.fileData = inputStreamToByte(filePath);//文件路径
fileObj.filePath = filePath;
//使用媒体消息分享
WXMediaMessage msg = new WXMediaMessage(fileObj);
msg.title = title;
//发送请求
SendMessageToWX.Req req = new SendMessageToWX.Req();
//创建唯一标识
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
ShareManager.getInstance().sendReq(req);
}
/**
* 将输入的流转换为byte数组
*
* @return byte数组
*/
public static byte[] inputStreamToByte(String path) {
try {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = fis.read()) != -1) {
bytestream.write(ch);
}
byte imgdata[] = bytestream.toByteArray();
bytestream.close();
return imgdata;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据url获取文件名称
*
* @param path
* @return
*/
public static String getFileName(String path) {
String str;
int pos1 = path.lastIndexOf('/');
int pos2 = path.lastIndexOf('\\');
int pos = Math.max(pos1, pos2);
if (pos < 0)
str = null;
else
str = path.substring(pos + 1);
return str;
}
}
@beilly

This comment has been minimized.

Copy link
Owner Author

beilly commented Apr 13, 2017

ShareManager.getInstance() use to get the Object of IWXAPI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.