app端实现上传pdf完整代码
时间: 2023-12-06 18:02:22 浏览: 90
这里提供一个使用HTTP协议上传pdf文件的示例代码,仅供参考:
```java
import android.os.AsyncTask;
import android.util.Log;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UploadPdfTask extends AsyncTask<String, Integer, String> {
private static final String TAG = "UploadPdfTask";
private String mFilePath;
private String mServerUrl;
private int mResponseCode;
public UploadPdfTask(String filePath, String serverUrl) {
mFilePath = filePath;
mServerUrl = serverUrl;
}
@Override
protected String doInBackground(String... params) {
String result = null;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
FileInputStream inputStream = null;
String boundary = "===" + System.currentTimeMillis() + "===";
try {
URL url = new URL(mServerUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
File file = new File(mFilePath);
inputStream = new FileInputStream(file);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
mResponseCode = connection.getResponseCode();
if (mResponseCode == 200) {
result = "上传成功";
} else {
result = "上传失败";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute: " + s);
if (mResponseCode == 200) {
// 上传成功
} else {
// 上传失败
}
}
}
```
使用方法:
```java
String filePath = "/sdcard/test.pdf";
String serverUrl = "http://example.com/upload";
new UploadPdfTask(filePath, serverUrl).execute();
```
需要注意的是,上面代码中的`serverUrl`需要替换成你自己的服务器地址,同时还需要根据你的实际情况修改一些其他参数。
阅读全文
相关推荐


















