Android中如何实现带进度的文件上传进度条实现

没有更多推荐了,
不良信息举报
举报内容:
android实现带进度条的文件上传
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!博客分类:
这里小结下,如何用android的模拟器去创建一个sdcard,并且学习如何在android中去下载
一个网上的文件,保存到android,并且下载时,会显示一个进度条
1 页面结构,提供一个button,点BUTTON时,去下载一个图片,main.xml设计如下:
&?xml version="1.0" encoding="utf-8"?&
&LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
&& android:orientation="vertical"
&& android:layout_width="fill_parent"
&& android:layout_height="fill_parent"
&& &
&TextView&
&& android:layout_width="fill_parent"
&& android:layout_height="wrap_content"
&& android:text="@string/hello"
&& /&
&Button
&&& android:text="Start long running task.."
&&& android:id="@+id/startBtn"
&&& android:layout_width="fill_parent"
&&& android:layout_height="wrap_content"&
&/Button&
&/LinearLayout&
2 主程序
&& package com.
import java.io.BufferedInputS
import java.io.FileOutputS
import java.io.InputS
import java.io.OutputS
import java.net.URL;
import java.net.URLC
import android.app.A
import android.app.D
import android.app.ProgressD
import android.os.AsyncT
import android.os.B
import android.util.L
import android.view.V
import android.view.View.OnClickL
import android.widget.B
public class AndroAsync extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
&&& private Button startB
&&& private ProgressDialog mProgressD
&&&
&&& /** Called when the activity is first created. */
&&& @Override
&&& public void onCreate(Bundle savedInstanceState) {
&&&&&&& super.onCreate(savedInstanceState);
&&&&&&& setContentView(R.layout.main);
&&&&&&& startBtn = (Button)findViewById(R.id.startBtn);
&&&&&&& startBtn.setOnClickListener(new OnClickListener(){
&&&&&&&&&&& public void onClick(View v) {
&&&&&&&&&&&&&&& startDownload();
&&&&&&&&&&& }
&&&&&&& });
&&& }
&&& private void startDownload() {
&&&&&&& String url = "http://image-
7.verycd.com/0ddfdc2(120x120)/thumb.jpg";
&&&&&&& new DownloadFileAsync().execute(url);
&&& }
&&& @Override
&&& protected Dialog onCreateDialog(int id) {
&&&&&&& switch (id) {
&&&&&&&&&&& case DIALOG_DOWNLOAD_PROGRESS:
&&&&&&&&&&&&&&& mProgressDialog = new ProgressDialog(this);
&&&&&&&&&&&&&&& mProgressDialog.setMessage("Downloading file..");
&&&&&&&&&&&&&&& mProgressDialog.setProgressStyle
(ProgressDialog.STYLE_HORIZONTAL);
&&&&&&&&&&&&&&& mProgressDialog.setCancelable(false);
&&&&&&&&&&&&&&& mProgressDialog.show();
&&&&&&&&&&&&&&& return mProgressD
&&&&&&&&&&& default:
&&&&&&&&&&&&&&&
&&&&&&& }
&&& }
&&& class DownloadFileAsync extends AsyncTask&String, String, String& {
&&&&&&&
&&&&&&& @Override
&&&&&&& protected void onPreExecute() {
&&&&&&&&&&& super.onPreExecute();
&&&&&&&&&&& showDialog(DIALOG_DOWNLOAD_PROGRESS);
&&&&&&& }
&&&&&&& @Override
&&&&&&& protected String doInBackground(String... aurl) {
&&&&&&&&&&&
&&&&&&&&&&& try {
&&&&&&&&&&&&&&& URL url = new URL(aurl[0]);
&&&&&&&&&&&&&&& URLConnection conexion = url.openConnection();
&&&&&&&&&&&&&&& conexion.connect();
&&&&&&&&&&&&&&& int lenghtOfFile = conexion.getContentLength();
&&&&&&&&&&&&&&& Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
&&&&&&&&&&&&&&& InputStream input = new BufferedInputStream(url.openStream());
&&&&&&&&&&&&&&& OutputStream output = new FileOutputStream
("/sdcard/picture.jpg");
&&&&&&&&&&&&&&& byte data[] = new byte[1024];
&&&&&&&&&&&&&&& long total = 0;
&&&&&&&&&&&&&&& while ((count = input.read(data)) != -1) {
&&&&&&&&&&&&&&&&&&& total +=
&&&&&&&&&&&&&&&&&&& publishProgress(""+(int)((total*100)/lenghtOfFile));
&&&&&&&&&&&&&&&&&&& output.write(data, 0, count);
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& output.flush();
&&&&&&&&&&&&&&& output.close();
&&&&&&&&&&&&&&& input.close();
&&&&&&&&&&& } catch (Exception e) {
&&&&&&&&&&&
&&&&&&&&&&&
Log.e("error",e.getMessage().toString());
&&&&&&&&&&&
System.out.println(e.getMessage().toString());
&&&&&&&&&&& }
&&&&&&&&&&&
&&&&&&& }
&&&&&&& protected void onProgressUpdate(String... progress) {
&&&&&&&&&&&& Log.d("ANDRO_ASYNC",progress[0]);
&&&&&&&&&&&& mProgressDialog.setProgress(Integer.parseInt(progress[0]));
&&&&&&& }
&&&&&&& @Override
&&&&&&& protected void onPostExecute(String unused) {
&&&&&&&&&&& dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
&&&&&&& }
&&& }
& 注意这里,在startdownload 方法中,调用了DownloadFileAsync内部类,这个内部类充
分利用了AsyncTask的异步工作特性,是很方便的,其中注意doInBackground(这个阶段下
载图片),onProgressUpdate是让进度条完成后消失。
最后,要记得在androidmanifest.xml中的&/application&后加入
&&& &uses-permission android:name="android.permission.INTERNET" /&
让能有访问互联网的能力
3 下面讲解下其中如何用到的,把图片保存到sdcard中去,由于是模拟器,因此
只能在磁盘上模拟一个IMG文件来充当模拟,步骤如下:
& 1) 打开cmd,进入Android SDK安装路径下的tools目录下,输入如下命令:
mksdcard 1024M sdcard.img
该命令会在当前目录下生成一个sdcard.img文件,该文件是Android模拟器的SD卡镜像文件
。1024M表示SD卡有1024M大小,即1G容量。目前Android支持8M~128G的SD卡。
& 2) 运行带sdcard的模拟器
&&& A 在cmd中启动带有sdcard的模拟器
进入Android SDK安装路径下的tools目录中,运行下面命令:
emulator -avd name_avd -sdcard sdcard.img
其中,name_avd是已有的模拟器的名字,sdcard.img是第一步创建的SD卡镜像文件。
&&& B& 在eclipse中,新建模拟器的时候,指定SD卡镜像文件的路径,并且加入对SD卡的支持选项
打开eclipse,进入:window-&android SDK and AVD manager,
然后在create avd的时候,在SD CARD中选择"FILE",然后再选择
3)如何看SDCARD中的文件
& 1)在cmd中,进入Android SDK的安装路径下的tools目录中,运行命令:
adb push E:\abc.jpg sdcard/abc.jpg
其中,E:\test.3gp 是本地要上传的文件,sdcard/abc.jpg 为上传到SD卡中的路径。
注意:adb push 电脑路径 模拟器路径
在电脑路径中,必须使用“\”,在模拟器路径中必须使用“/”,并且模拟器的根路径是只
2 ) 在eclipse环境中
在设置了RUN的命令参数后,RUN一个应用程序,然后使用DDMS的File Explorer工具导入导出文
件。打开DDMS工具,在eclipse的windows-&Open Perspective-&Other...里面打开DDMS工具,在
DDMS工具的File Explorer标签里面选择sdcard目录导入导出文件,
浏览: 5883680 次
来自: 广州
有些扩展名为null
非常感谢!!!!!!!!!
https://zhuban.me竹板共享 - 高效便捷的文档 ...
kris_zhang 写道如果有多个@Primary 会怎么样 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Android使用OkHttp实现带进度的上传下载
先贴上MainActivity.java
package cn.edu.zafu.
import android.os.B
import android.support.v7.app.AppCompatA
import android.util.L
import android.view.V
import android.widget.B
import android.widget.ProgressB
import android.widget.T
import okhttp3.C
import okhttp3.H
import okhttp3.MediaT
import okhttp3.MultipartB
import okhttp3.OkHttpC
import okhttp3.R
import okhttp3.RequestB
import okhttp3.R
import java.io.F
import java.io.IOE
import java.util.concurrent.TimeU
import cn.edu.zafu.coreprogress.helper.ProgressH
import cn.edu.zafu.coreprogress.listener.ProgressL
import cn.edu.zafu.coreprogress.listener.impl.UIProgressL
public class MainActivity extends AppCompatActivity {
private static final OkHttpClient client = new OkHttpClient.Builder()
//设置超时,不设置可能会报异常
.connectTimeout(1000, TimeUnit.MINUTES)
.readTimeout(1000, TimeUnit.MINUTES)
.writeTimeout(1000, TimeUnit.MINUTES)
private Button upload,
private ProgressBar uploadProgress,downloadP
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
private void initView() {
uploadProgress= (ProgressBar) findViewById(R.id.upload_progress);
downloadProgeress= (ProgressBar) findViewById(R.id.download_progress);
upload= (Button) findViewById(R.id.upload);
download= (Button) findViewById(R.id.download);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
download.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
download();
private void download() {
//这个是非ui线程回调,不可直接操作UI
final ProgressListener progressResponseListener = new ProgressListener() {
public void onProgress(long bytesRead, long contentLength, boolean done) {
Log.e("TAG", "bytesRead:" + bytesRead);
Log.e("TAG", "contentLength:" + contentLength);
Log.e("TAG", "done:" + done);
if (contentLength != -1) {
//长度未知的情况下回返回-1
Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
Log.e("TAG", "================================");
//这个是ui线程回调,可直接操作UI
final UIProgressListener uiProgressResponseListener = new UIProgressListener() {
public void onUIProgress(long bytesRead, long contentLength, boolean done) {
Log.e("TAG", "bytesRead:" + bytesRead);
Log.e("TAG", "contentLength:" + contentLength);
Log.e("TAG", "done:" + done);
if (contentLength != -1) {
//长度未知的情况下回返回-1
Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
Log.e("TAG", "================================");
//ui层回调
downloadProgeress.setProgress((int) ((100 * bytesRead) / contentLength));
//Toast.makeText(getApplicationContext(), bytesRead + " " + contentLength + " " + done, Toast.LENGTH_LONG).show();
public void onUIStart(long bytesRead, long contentLength, boolean done) {
super.onUIStart(bytesRead, contentLength, done);
Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_SHORT).show();
public void onUIFinish(long bytesRead, long contentLength, boolean done) {
super.onUIFinish(bytesRead, contentLength, done);
Toast.makeText(getApplicationContext(),"end",Toast.LENGTH_SHORT).show();
//构造请求
final Request request1 = new Request.Builder()
.url("http://121.41.119.107:81/test/1.doc")
//包装Response使其支持进度回调
ProgressHelper.addProgressResponseListener(client, uiProgressResponseListener).newCall(request1).enqueue(new Callback() {
public void onFailure(Request request, IOException e) {
Log.e("TAG", "error ", e);
public void onResponse(Response response) throws IOException {
Log.e("TAG", response.body().string());
private void upload() {
File file = new File("/sdcard/1.doc");
//此文件必须在手机上存在,实际情况下请自行修改,这个目录下的文件只是在我手机中存在。
//这个是非ui线程回调,不可直接操作UI
final ProgressListener progressListener = new ProgressListener() {
public void onProgress(long bytesWrite, long contentLength, boolean done) {
Log.e("TAG", "bytesWrite:" + bytesWrite);
Log.e("TAG", "contentLength" + contentLength);
Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
Log.e("TAG", "done:" + done);
Log.e("TAG", "================================");
//这个是ui线程回调,可直接操作UI
final UIProgressListener uiProgressRequestListener = new UIProgressListener() {
public void onUIProgress(long bytesWrite, long contentLength, boolean done) {
Log.e("TAG", "bytesWrite:" + bytesWrite);
Log.e("TAG", "contentLength" + contentLength);
Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
Log.e("TAG", "done:" + done);
Log.e("TAG", "================================");
//ui层回调
uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
//Toast.makeText(getApplicationContext(), bytesWrite + " " + contentLength + " " + done, Toast.LENGTH_LONG).show();
public void onUIStart(long bytesWrite, long contentLength, boolean done) {
super.onUIStart(bytesWrite, contentLength, done);
Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_SHORT).show();
public void onUIFinish(long bytesWrite, long contentLength, boolean done) {
super.onUIFinish(bytesWrite, contentLength, done);
Toast.makeText(getApplicationContext(),"end",Toast.LENGTH_SHORT).show();
//构造上传请求,类似web表单
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("hello", "android")
.addFormDataPart("photo", file.getName(), RequestBody.create(null, file))
.addPart(Headers.of("Content-Disposition", "form- name=\"another\";filename=\"another.dex\""), RequestBody.create(MediaType.parse("application/octet-stream"), file))
//进行包装,使其支持进度回调
final Request request = new Request.Builder().url("http://121.41.119.107:81/test/result.php").post(ProgressHelper.addProgressRequestListener(requestBody, uiProgressRequestListener)).build();
//开始请求
client.newCall(request).enqueue(new Callback() {
public void onFailure(Request request, IOException e) {
Log.e("TAG", "error ", e);
public void onResponse(Response response) throws IOException {
Log.e("TAG", response.body().string());
紧接着就是布局文件了
layout_main.xml
&LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"&
&ProgressBar
android:id="@+id/upload_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:id="@+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload"/&
&ProgressBar
android:id="@+id/download_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:id="@+id/download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download"/&
&/LinearLayout&
另外别忘了给配置清单文件添加权限
&uses-permission android:name="android.permission.INTERNET"/&
&uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&
还有一个就是添加依赖了
dependencies {
compile 'cn.edu.zafu:coreprogress:0.0.3'
以下问题需要添加
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
源代码地址:https://github.com/newcaoguo/CoreProgress.git
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
在使用ajaxForm方法之前,首先需要安装form.js的插件,网上有: 一.首先说用法,ajaxForm可以接收0或1个参数,该参数可以是一个变量.一个对象或回调函数,这个对象主要有以下参数: v ...
访问网络最主要的也就是 http协议了. http协议很简单,但是很重要. 直接上代码了,里面都是1个代码块 代码块的,用哪一部分直接拷出去用就好了. 1.访问网络用 get 和 post
自己组拼 ...
序 前面一篇文章介绍了Retrofit2的基本使用,这篇文章接着介绍使用Retrofit2实现文件上传和文件下载,以及上传下载过程中如何实现进度的显示. 文件上传 定义接口 1 2 3 @Multip ...
原文网址:http://blog.csdn.net/tanghua0809/article/details/ 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...
请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在&Andr ...
直接上代码,其中上传功能需要自己配置允许跨域的文件服务器地址~ 或者将html文件贴到您的站点下同源上传也OK. 支持: 不同尺寸图片获取. 原图缩小放大. 原图移动. 选择框大小改变. 下载选中的区 ...
package com.why. import java.io.DataInputS import java.io.F import java.io.FileInputSt ...
jar不能低于此版本,JDK1.6以上,否则户报错 &dependency& &groupId&commons-fileupload&/groupId& &a ...
Given a singly linked list, determine if it is a palindrome. Follow up:Could you do it in O(n) time
下载地址是http://dev.mysql.com/downloads/mirror.php?id=403020 请先注册登录后才能下载mysql-connector-net-6.3.7.msi这个文 ...
双击修改某项值 $(function() { $('td.breakword').dblclick(function(){ $(this).addClass('input').html('&in ...
T1表 万条数据,(插入时间36分钟,count(*)查询19秒,空间占用670M左右) 1.真正充分的利用索引比如like '张%' 就是符合SARG(符合扫描参数)标准而like
以下内容援引自&C Primer Plus&中文版第五版Page95 Sizeof运算符以字节为单位返回其操作数的大小.(在C中,1个字节被定义为char类型所占用空间的大小.在过去,1个 ...
&?phpini_set(&error_reporting&,&E_ALL & ~E_NOTICE&);?& &head&&lt ...
LTE用户文档 (如有不当的地方,欢迎指正!) 16 Network Attachment(网络连接)
正如前面章节 Basic simulation program 所述,连接用户到基站时通过调 ...
一.查找文件 使用快捷键[ctrl+shift+R]弹出弹出文件查找框,如下图所示: 二.查找包含某个字符串的文件 使用快捷键[ctrl+H]在弹出对话框中选File Search选项,然后在第一个文 ...
[删除节点] 步骤: ① 找到对象 ② 找到他的父对象 parentObj ③ parentObj.removeChild(子对象); [例] &!DOCTYPE html& &ht ...
利滚利计算在数学上是否有一个简单的公式,我不知道,但作为程序员,这个算法实现起来就是小菜一碟.作为插件发布,是因为程序确实简单,也方便Chome浏览器使用者安装.如果你也想使用一下Chrome插件,参 ...&nbsp>&nbsp
&nbsp>&nbsp
&nbsp>&nbsp
Android 上传文件到服务端,并显示进度条
摘要:最近在做上传文件的服务,简单看了网上的教程。结合实践共享出代码。由于网上的大多数没有服务端的代码,这可不行呀,没服务端怎么调试呢。Ok,先上代码。Android上传比较简单,主要用到的是HttpURLConnection类,然后加一个进度条组件。privateProgressBarmPgBclassUploadTaskextendsAsyncTask{privateDataOutputStreamoutputStream=privateStringfileNa
最近在做上传文件的服务,简单看了网上的教程。结合实践共享出代码。
由于网上的大多数没有服务端的代码,这可不行呀,没服务端怎么调试呢。
Ok,先上代码。
Android 上传比较简单,主要用到的是 HttpURLConnection 类,然后加一个进度条组件。
private ProgressBar mPgB
class UploadTask extends AsyncTask
private DataOutputStream outputStream =
private String fileN
private String mLineEnd = &/r/n&;
private String mTwoHyphens = &--&;
private String boundary = &*****&;
File uploadF
long mTtotalS // Get size of file, bytes
public UploadTask(String fileName,String uri){
this.fileName = fileN
this.uri =
uploadFile= new File(fileName);
mTtotalSize = uploadFile.length();
* 开始上传文件
* @param objects
protected Void doInBackground(Object... objects) {
long length = 0;
int mBytesRead, mbytesAvailable, mBufferS
int maxBufferSize = 256 * 1024;// 256KB
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//如果有必要则可以设置Cookie
// conn.setRequestProperty(&Cookie&,&JSESSIONID=&+cookie);
// Set size of every block for post
con.setChunkedStreamingMode(256 * 1024);// 256KB
// Allow Inputs &; Outputs
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
// Enable POST method
con.setRequestMethod(&POST&);
con.setRequestProperty(&Connection&, &Keep-Alive&);
con.setRequestProperty(&Charset&, &UTF-8&);
con.setRequestProperty(&Content-Type&,
&multipart/form-boundary=& + boundary);
outputStream = new DataOutputStream(
con.getOutputStream());
outputStream.writeBytes(mTwoHyphens + boundary + mLineEnd);
outputStream.writeBytes(&Content-Disposition: form- name=/&file/&; filename=/&& + fileName + &/&& + mLineEnd);
outputStream.writeBytes(&Content-Type:application/octet-stream /r/n&);
outputStream.writeBytes(mLineEnd);
mbytesAvailable = fileInputStream.available();
mBufferSize = Math.min(mbytesAvailable, maxBufferSize);
buffer = new byte[mBufferSize];
// Read file
mBytesRead = fileInputStream.read(buffer, 0, mBufferSize);
while (mBytesRead & 0) {
outputStream.write(buffer, 0, mBufferSize);
length += mBufferS
publishProgress((int) ((length * 100) / mTtotalSize));
mbytesAvailable = fileInputStream.available();
mBufferSize = Math.min(mbytesAvailable, maxBufferSize);
mBytesRead = fileInputStream.read(buffer, 0, mBufferSize);
outputStream.writeBytes(mLineEnd);
outputStream.writeBytes(mTwoHyphens + boundary + mTwoHyphens
+ mLineEnd);
publishProgress(100);
// Responses from the server (code and message)
int serverResponseCode = con.getResponseCode();
String serverResponseMessage = con.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
Log.v(TAG,&uploadError&);
protected void onProgressUpdate(Integer... progress) {
mPgBar.setProgress(progress[0]);
主要流程为继承AsyncTask,然后使用HttpURLConnection 去上传文件。代码比较简单,就不一一讲解了。
其中要注意的是需要在
outputStream.writeBytes(&Content-Disposition: form- name=/&file/&; filename=/&& + fileName + &/&& + mLineEnd);
将name 设置为web 请求的参数名,由于我的服务端是将文件设置为file参数,所以我可以直接填file .所以大家可以根据实际情况作相应修改。
那么接着上服务端代码,服务端主要使用status 2框架作请求。那么我们就需要进行封装。
//上传文件集合
private List
//上传文件名集合
private List
//上传文件内容类型集合
private List
fileContentT
public List
getFile() {
public void setFile(List
this.file =
public List
getFileFileName() {
return fileFileN
public void setFileFileName(List
fileFileName) {
this.fileFileName = fileFileN
public List
getFileContentType() {
return fileContentT
public void setFileContentType(List
fileContentType) {
this.fileContentType = fileContentT
采用了多文件上传的方法,定义了List 集合。
那么处理文件上传的action ,由于是测试方法。这里就定义为testUpload
public String testUpload()throws Exception{
System.out.println(&success&);
uploadFile(0);
return SUCCESS;
到这里就已经才不多完成动作了,现在需要开始写上传的方法 uploadFile(int index),由于定义file 为多文件上传,而我们上传只上传了一个文件,所以这里参数为0
* 上传功能
* @param i
* @throws FileNotFoundException
* @throws IOException
private String uploadFile(int i) throws FileNotFoundException, IOException {
InputStream in = new FileInputStream(file.get(i));
//String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);
String dir = &D://UploadData/&;
File uploadFile = new File(dir,StringUtils.getUUID()+getFile( this.getFileFileName().get(i)));
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
while ((length = in.read(buffer)) & 0) {
out.write(buffer, 0, length);
in.close();
out.close();
//然后进行计算
return uploadFile.getAbsolutePath();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
上面方法为将缓存区域的文件 然后搞到了D://UploadData/ 文件中,然后以自己的格式进行命名,这里我使用了电脑的UUID和文件名进行组合,确保我复制过来的文件不重复。
最后上传成功之后返回文件的真实地址。
ok,写到这里上传文件的功能基本上做完了。最后只剩下配置action 动作。
ok,我们打开status.xml 文件进行配置
这里主要定义上传文件的临时存放位置,然后大小限制。
大家可以根据实际情况进行配置。
最后上传一张效果图。
以上是的内容,更多
的内容,请您使用右上方搜索功能获取相关信息。
若你要投稿、删除文章请联系邮箱:zixun-group@service.aliyun.com,工作人员会在五个工作日内给你回复。
云服务器 ECS
可弹性伸缩、安全稳定、简单易用
&40.8元/月起
预测未发生的攻击
&24元/月起
为您提供0门槛上云实践机会
你可能还喜欢
你可能感兴趣
阿里云教程中心为您免费提供
Android 上传文件到服务端,并显示进度条相关信息,包括
的信息,所有Android 上传文件到服务端,并显示进度条相关内容均不代表阿里云的意见!投稿删除文章请联系邮箱:zixun-group@service.aliyun.com,工作人员会在五个工作日内答复
售前咨询热线
支持与服务
资源和社区
关注阿里云
International

我要回帖

更多关于 带进度条的文件上传 的文章

 

随机推荐