最近要用到想服务器上传文件数据,先抄个作业,明天研究之后再做定论:
public
void
btnUpload(View v){
// newName = "base.jpg";
newName =
"VideoTest.mp4"
;
uploadFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+newName;
uploadFile =
new
File(uploadFilePath);
if
(!uploadFile.exists()) {
Toast.makeText(MainActivity.
this
,
"文件不存在,请修改文件路径"
, Toast.LENGTH_SHORT).show();
return
;
}
actionUrl =
"http://182.92.152.12:10898/check_again"
;
// actionUrl = "http://server.jeasonlzy.com/OkHttpUtils/upload";
Map params =
new
HashMap<>();
params.put(
"info"
,
"panbaomeng"
);
OkHttpUtils.post()
.addFile(
"newName"
,newName,uploadFile)
.url(actionUrl)
.params(params)
.build()
.execute(
new
MyStringCallback());
}
public
class
MyStringCallback
extends
StringCallback
{
@Override
public
void
onBefore(Request request,
int
id)
{
setTitle(
"loading..."
);
}
@Override
public
void
onAfter(
int
id)
{
setTitle(
"Sample-okHttp"
);
}
@Override
public
void
onError(Call call, Exception e,
int
id)
{
e.printStackTrace();
Log.e(
"onError:"
,e.getMessage());
}
@Override
public
void
onResponse(String response,
int
id)
{
Log.e(
"onResponse"
, response);
switch
(id)
{
case
100
:
Toast.makeText(MainActivity.
this
,
"http"
, Toast.LENGTH_SHORT).show();
break
;
case
101
:
Toast.makeText(MainActivity.
this
,
"https"
, Toast.LENGTH_SHORT).show();
break
;
}
}
@Override
public
void
inProgress(
float
progress,
long
total,
int
id)
{
// Log.e(TAG, "inProgress:" + progress);
// mProgressBar.setProgress((int) (100 * progress));
}
}