我已经在Android中开发了一段时间的应用程序,现在我需要通过此应用程序将图像上传到服务器。问题是我真的不知道如何在后端(这是服务器端)这样做。我已经阅读了很多关于通过httpmime
库和使用multipart
发送图像的内容,但是没有太多关于接收图像的服务器端服务。
我需要使用像MVC3或WCF这样的东西,因为我们这里的服务器是IIS,我还没有找到很多关于如何使用这个模型的方法。因此,任何有关如何使用此模型实现这一目标的教程或指南都是我需要的,任何帮助也将非常感激。
答案 0 :(得分:1)
您可以通过HTTP POST发布文件
public String sendFilePost(String urlServer, String pathToOurFile){
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
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();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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)
String serverResponseMessage = connection.getResponseMessage();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
String rrrr = response.toString();
rd.close();
fileInputStream.close();
outputStream.flush();
outputStream.close();
return rrrr;
}
catch (Exception ex)
{
return "Something went wrong!";
}
}