使用socket将文件从Android上传到服务器

3

我正在开发Android应用程序。在提问之前,我查看了很多帖子。我想使用java中的socket从Android手机上传文件。在服务器端,应该使用什么类型的应用程序来处理?假设使用java编写服务器端。应该使用什么类型的项目? 对于Java应用程序,我只知道服务器主机--Tomcat。

1个回答

3

在您的情况下(由于服务器具有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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接