我想将多张照片上传到SFTP server
但是使用以下代码只会上传一张照片。请任何人知道我哪里出错或者有更好的方法
private class uploadFileOnFTPServerAsync extends
AsyncTask<Void, Void, Void> {
ProgressDialog pdDialog;
@Override
protected void onPreExecute() {
try {
pdDialog = new ProgressDialog(MediaFileAttachmentActivity.this);
pdDialog.setMessage("Loading please wait..");
pdDialog.show();
pdDialog.setCancelable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected Void doInBackground(Void... params) {
if (mediaDataList.size() > 0) {
for (int i = 0; i < mediaDataList.size(); i++) {
if (mediaDataList.get(i).getMediaFTPPath()
.equalsIgnoreCase("")) {
uploadFileonSFTP(mediaDataList.get(i)
.getmFile(), mediaDataList.get(i)
.getMediaName(), "images");
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pdDialog.dismiss();
MediaFileAttachmentActivity.this.finish();
Toast.makeText(MediaFileAttachmentActivity.this,
"Attachments saved successfully", Toast.LENGTH_SHORT)
.show();
}
}
private void uploadFileonSFTP(final File file2, String app_filename,
String type){
try{
new Thread(new Runnable() {
@Override
public void run() {
connectToSFTP(file2);
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectToSFTP(File file2)
{
try {
JSch jsch = new JSch();
session = jsch.getSession(USER_NAME,SERVER_ADDRESS,PORT_NO);
session.setPassword(AppSingleton.getInstance().getPASSWORD());
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
channelSftp.cd(AppSingleton.getInstance().getPATH());
// File f = new File(file2);
channelSftp.put(new FileInputStream(file2), file2.getName());
session.disconnect();
channel.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
我通过创建一个线程而不是Asynctask
解决了这个问题private void executeThread() {
final ProgressDialog pdDialog;
pdDialog = new ProgressDialog(MediaFileAttachmentActivity.this);
pdDialog.setMessage("Loading please wait..");
pdDialog.show();
pdDialog.setCancelable(false);
new Thread(new Runnable() {
@Override
public void run() {
if (mediaDataList.size() > 0) {
for (int i = 0; i < mediaDataList.size(); i++) {
if (mediaDataList.get(i).getMediaFTPPath()
.equalsIgnoreCase("")) {
uploadFileonSFTP(mediaDataList.get(i)
.getmFile(), mediaDataList.get(i)
.getMediaName(), "images");
}
}
}
handler.post(new Runnable() {
@Override
public void run() {
pdDialog.dismiss();
MediaFileAttachmentActivity.this.finish();
Toast.makeText(MediaFileAttachmentActivity.this,
"Attachments saved successfully", Toast.LENGTH_SHORT)
.show();
}
});
}
}).start();
}