❶ 如何將手機自身作為伺服器上傳文件
這個有幾個不同情況:
手機安裝ftp客戶端,AndFTP是android設備上的一款FTP/SFTP/FTPS客戶端軟體,可以實現和電腦一樣的文件傳輸方式,直接連接你的空間即可傳輸。
手機沒有客戶端軟體,可以採用中間方式,使用網頁傳輸,叫做webftp工具,就是利用網頁數據傳輸的方式,打開webftp網站,輸入空間的FTP信息連接即可傳輸文件。
注意一點,使用webftp需要在空間後台先設置允許連接的IP地址,使空間伺服器允許webftp連接並向其傳輸文件。
❷ 如何向微信伺服器上傳文件
在某些開發中,我們需要向微信伺服器發送文件,比如圖片,語音等等,藉助微信伺服器來實現我們的一些需求,具體的實現如下:
/**
* 向微信伺服器上傳文件
*
* @param accessToken
* 進入的介面
* @param type
* 文件類型(語音或者是圖片)(對於文檔不適合)
* @param url
* 文件的存儲路徑
* @return json的格式{"media_id":
* "nrSKG2eY1E__pdiNiSXuijbCmWWc8unzBQ"
* ,"created_at":1408436207,"type":"image"}
*/
public JSONObject uploadFile(String fileType, String filePath)
throws Exception {
GetExistAccessToken getExistAccessToken = GetExistAccessToken.getInstance();
String accessToken = getExistAccessToken.getExistAccessToken();
// 上傳文件請求路徑
String action = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="
+ accessToken + "&type=" + fileType;
URL url = new URL(action);
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("上傳的文件不存在");
}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST"); // 以Post方式提交表單,默認get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用緩存
// 設置請求頭信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 設置邊界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ BOUNDARY);
// 請求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必須多兩道線
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 獲得輸出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 輸出表頭
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 結尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後數據分隔線
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
// 定義BufferedReader輸入流來讀取URL的響應
reader = new BufferedReader(new InputStreamReader(con
.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("發送POST請求出現異常!" + e);
e.printStackTrace();
throw new IOException("數據讀取異常");
} finally {
if (reader != null) {
reader.close();
}
}
JSONObject jsonObj = new JSONObject(result);
return jsonObj;
}