gpt4 book ai didi

java - Android:显示真实上传进度百分比

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:16 25 4
gpt4 key购买 nike

我需要将生成的大型 pdf 文件上传到服务器并向用户显示上传进度。但问题是我从OutputStream获取的百分比并不是真正的进度,因为OutputStream进度100%后,仍然无法从服务器获取响应代码(需要等待更多)

请帮我解决这个问题。谢谢。

** 了解更多信息:总上传时间为 15 分钟,但进度百分比在一秒内完成。

class UploadPdf extends AsyncTask<String, Integer, String> {

private Activity activity;
private String orderId = "";
private String filenamepdf = "";
private String filenamezip = "";
private int dpi = 640;
public ImageCreator mImageCreator;

public UploadPdf(Activity activity) {
this.activity = activity;
}

@Override
protected String doInBackground(String... strings) {
orderId = strings[0];
filenamepdf = orderId + ".pdf";

String uploadStatus = uploadFileToServer();
return uploadStatus;
}

@Override
protected void onProgressUpdate(Integer... progress) {
//Update progress
updateProgress(progress[0]);
}

@Override
protected void onPostExecute(String result) {
//Show result
try {
JSONObject obj = new JSONObject(result);
if(obj.getString("status").equals("success")) {
uploadSuccess();
} else {
errorContainer.setVisibility(View.VISIBLE);
}

} catch (Exception ex) {
errorContainer.setVisibility(View.VISIBLE);
}
}

private String uploadFileToServer() {
Log.d(LOGTAG, "uploadFileToServer");
String urlString = Constants.API_BASE_URL + Constants.API_CREATE_UPLOAD_FILE;

String response = null;
String attachmentName = "attachment";
String attachmentFileName = "attachment";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

try {
File file = new File(filenamepdf);
MultipartUtility multipart = new MultipartUtility(urlString, "UTF-8", getApplicationContext());

multipart.addFormField("order_id", orderId);
multipart.addFilePart("album_image_path", file);

List<String> responseReturn = multipart.finish();
Log.e(LOGTAG, "SERVER REPLIED:");
response = "";
for (String line : responseReturn) {
Log.e(LOGTAG, "Upload Files Response:::" + line);
response += line;
}
} catch (Exception ex) {
Log.e(LOGTAG, "Failed:" + ex.getMessage());
}

Log.e(LOGTAG, "Response:" + response);
return response;
}

public class MultipartUtility {
private final String LOGTAG = "MultipartUtility";
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
Context context;

/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartUtility(String requestURL, String charset, Context context)
throws IOException {
this.charset = charset;
this.context = context;

// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}

/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value) {
Log.d(LOGTAG, "name: " + name + ", value: " + value);
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}


/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName();
Log.d(LOGTAG, fieldName);
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();

FileInputStream inputStream = new FileInputStream(uploadFile);

byte[] bytes = new byte[(int) uploadFile.length()];
int byteLength = bytes.length;
byte[] buffer = new byte[4096];
int bytesRead = -1;
int sendByte = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
sendByte += bytesRead;
int progress = (int)(sendByte / (float) byteLength * 100);
Log.d(LOGTAG, "bytesRead: " + bytesRead + ", byteLength: " + byteLength + ", progress: " + progress);
publishProgress(progress);
}
outputStream.flush();
Log.d(LOGTAG, "Read byte finish");
outputStream.close();
Log.d(LOGTAG, "Close output stream");

inputStream.close();
Log.d(LOGTAG, "Close input stream");
writer.append(LINE_FEED);
writer.flush();
Log.d(LOGTAG, "Writer flushed");
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}

public List<String> finish() throws IOException {
Log.d(LOGTAG, "Finishing");
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
Log.d(LOGTAG, "Line feed flushed");
writer.append("--" + boundary + "--").append(LINE_FEED);
Log.d(LOGTAG, "Last line flushed");
writer.close();
Log.d(LOGTAG, "Writer closed");

// checks server's status code first
int status = httpConn.getResponseCode();
Log.d(LOGTAG, "Server returned status: " + status);
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
}

最佳答案

首先,我建议使用 OKHTTP MultipartBody,这是更好的 api,这里使用的是同一个类,您可以像使用 MultiPart 实用程序一样使用

public class MultipartRequest {
public Context caller;
public MultipartBody.Builder builder;
private OkHttpClient client;

public MultipartRequest(Context caller) {
this.caller = caller;
this.builder = new MultipartBody.Builder();
this.builder.setType(MultipartBody.FORM);
this.client = new OkHttpClient();
}

public void addString(String name, String value) {
this.builder.addFormDataPart(name, value);
}

public void addFile(String name, String filePath, String fileName) {
this.builder.addFormDataPart(name, fileName, RequestBody.create(
MediaType.parse("image/jpeg"), new File(filePath)));
}

public void addTXTFile(String name, String filePath, String fileName) {
this.builder.addFormDataPart(name, fileName, RequestBody.create(
MediaType.parse("text/plain"), new File(filePath)));
}

public void addZipFile(String name, String filePath, String fileName)
{
this.builder.addFormDataPart(name, fileName, RequestBody.create(
MediaType.parse("application/zip"), new File(filePath)));
}

public String execute(String url,String header) {
RequestBody requestBody = null;
Request request = null;
Response response = null;

int code = 200;
String strResponse = null;

try {
requestBody = this.builder.build();
request = new Request.Builder().header("Authorization", header)
.url(url).post(requestBody).build();



Log.e("::::::: REQ :: " , ""+request);
response = client.newCall(request).execute();
Log.e("::::::: response :: " ,""+ response);

if (!response.isSuccessful())
throw new IOException();

code = response.networkResponse().code();

if (response.isSuccessful()) {
strResponse = response.body().string();
} else {

}
} catch (Exception e) {
Log.e("Exception", ""+e);

} finally {
requestBody = null;
request = null;
response = null;
builder = null;
if (client != null)
client = null;
System.gc();
}
return strResponse;
}
}

现在为了解决您对如何取得进展的担忧,这里提供了一个解决方案,请查看一下

OKHTTP 3 Tracking Multipart upload progress

这确实是一个很好的解决方案。

关于java - Android:显示真实上传进度百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com