gpt4 book ai didi

android - 将图像上传到服务器 - Android

转载 作者:行者123 更新时间:2023-11-30 03:05:00 27 4
gpt4 key购买 nike

我有 Rest Api 的链接和用 C sharp 上传图像的示例代码,但是如何使用 java 将图像从 android 上传到服务器同样的事情

这是示例代码

http://xx.xx.xxx.xx/restservice/photos

Sample code for uploading file:
string requestUrl = string.Format("{0}/UploadPhoto/{1}", url,filnm);
//file name should be uniqque
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "text/plain";
byte[] fileToSend = FileUpload1.FileBytes; //File bytes
request.ContentLength = fileToSend.Length;

using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);

你将如何使用 android

已编辑:

在您的回答的帮助下,我在这里编写了代码,但我收到了 404 连接响应和 ERROR ERROR

    public class ImageUploadToServer extends Activity {

TextView messageText;
Button uploadButton;

String upLoadServerUri = null;
String urlLink = "http://xx.xx.xxx.xx/restservice/photos/";
String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/myimg.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);

uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
uploadData();

}

public void uploadData ()
{

HttpURLConnection connection = null;
DataOutputStream outputStream = 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(path));

File sourceFile = new File(path);

FileInputStream fileInputStream = new FileInputStream(sourceFile);

URL url = new URL(urlLink);
connection = (HttpURLConnection) url.openConnection();

Log.d("Connection:", "Connection" + connection.getResponseCode());

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=\""
+ path + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

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);

fileInputStream.close();
outputStream.flush();
outputStream.close();

InputStream responseStream = new BufferedInputStream(connection.getInputStream());

BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();

String response = stringBuilder.toString();
Log.w("SERVER RESPONE: ", "Server Respone" + response);

responseStream.close();
connection.disconnect();

} catch (Exception ex) {
Log.i("UPLOAD ERROR", "ERROR ERROR");
}

}


}

最佳答案

我目前正在使用此代码将小视频上传到服务器(PHP 服务器端)。

请注意不再支持 apache HttpClient,因此 HttpURLConnection 是可行的方法。

    try {
FileInputStream fileInputStream = new FileInputStream(new File(
path));

URL url = new URL(urlLink);
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=\""
+ path + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

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);

fileInputStream.close();
outputStream.flush();
outputStream.close();

InputStream responseStream = new BufferedInputStream(connection.getInputStream());

BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();

String response = stringBuilder.toString();
Log.w("SERVER RESPONE: ", response);

responseStream.close();
connection.disconnect();

} catch (Exception ex) {
Log.i("UPLOAD ERROR", "ERROR ERROR");
}
}

关于android - 将图像上传到服务器 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com