使用插槽将文件从Android上传到服务器
问题描述:
我正在开发Android应用程序。在创建这个问题之前,我搜索了很多帖子。我想用java中的socket从android手机上传文件。服务器端应该是什么样的应用程序?假设在java.lang中写入服务器端应该是什么类型的项目?关于java应用程序的 ,我只知道服务器主机 - tomcat。使用插槽将文件从Android上传到服务器
答
你的情况(作为服务器有tomcat)如果你有服务器的URL,那么你可以使用HttpURLConnection上传任何文件到服务器。在服务器端逻辑应该被写入接收文件 例
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/sdcard/file_to_send.mp3"; //complete path of file from your android device
String urlServer = "http://192.168.10.1/handle_upload.do";// complete path of server
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
+1优秀的文章,也许人们所预料的服务器端,以配合这将是有益的什么样的代码的简要概述我。 – Elemental
Sunil,通过你的解决方案,这是否意味着我需要创建一个web服务或网站来接收文件?有没有办法从服务器端没有代码的客户端获取文件?像FTP一样? – user418751
检查SPK的FTP上传链接。它链接到一个预制的FTP类为您做上传。但请记住,使用标准的FTP上传可能是不安全的(因为任何人都可能窃取登录数据并滥用服务器!)。 – Mario