**了解更多信息:总上传时间为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,它是一个可以与使用MultipartUtility一样使用的类
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跟踪多部分上载进度
本文向大家介绍axios+Vue实现上传文件显示进度功能,包括了axios+Vue实现上传文件显示进度功能的使用技巧和注意事项,需要的朋友参考一下 一,前言 最近在用Vue,然后上传文件时需要显示进度,于是网上搜了一下,经过自己实测终于也弄明白了 二,效果 三,代码 HTML代码 CSS代码 JS代码 四,总结 1.其实单文件上传和多文件上传的区别就是 input标签中多了一个属性 multip
本文向大家介绍Android实现百分比下载进度条效果,包括了Android实现百分比下载进度条效果的使用技巧和注意事项,需要的朋友参考一下 现在很多APP中都会集成下载功能,所以有一个方便好看又实用的进度条来展示下载进度很有必要,也能提高用户体验,在这里我就把项目里的下载进度条抽取出来分享给大家,话不多说,先看效果图: 这个进度条是自定义的一个View,其中有一个自定义属性就是百分比文字的大小(也
本文向大家介绍JS实现批量上传文件并显示进度功能,包括了JS实现批量上传文件并显示进度功能的使用技巧和注意事项,需要的朋友参考一下 今天接受项目中要完成文件批量上传文件而且还要显示上传进度,一开始觉得这个应该不是很麻烦,当我在做的时候遇到了很多问题,很头疼啊。 不过看了别人写的代码,自己也测试过,发现网上好多都存在一些问题,并不是自己想要的。然后自己查阅各种资料,经过自己总结,最终完成了这个功能。
本文向大家介绍Jquery和BigFileUpload实现大文件上传及进度条显示,包括了Jquery和BigFileUpload实现大文件上传及进度条显示的使用技巧和注意事项,需要的朋友参考一下 实现方法:用到了高山来客 的bigfileupload组件,用高山来客的方法,弹出一个模式窗口,然后不停刷新获取进度,始终觉得体验感不好,于是想到用jquery来实现无刷新进度显示,因为提交页面后, 不能
问题内容: 我有上传表格,允许用户上传多个文件。我决定,如果文件很大,则进度条会很好。下面是我的源代码。我是jQuery的新手,通常我只会使用php,但是我发现ajax更加用户友好。 图像上传正常,数组发送到ajax,但进度条不动。实际上,调用这两个函数的console.log都不会产生这种情况。有没有正确的方法来调用我的ajax请求中的函数,以使此进度条正常工作。 beforeSubmit:be
本文向大家介绍基于Jquery插件Uploadify实现实时显示进度条上传图片,包括了基于Jquery插件Uploadify实现实时显示进度条上传图片的使用技巧和注意事项,需要的朋友参考一下 先了解了解Uploadify,具体内容如下 Uploadify是一个简单易用的多文件上传方案。作为一个Jquery插件,Uploadify使用简单,并具有高度的定制性。 Uploadify特性: Upload