gpt4 book ai didi

java - 从android上传文件到服务器失败

转载 作者:行者123 更新时间:2023-12-01 06:13:32 25 4
gpt4 key购买 nike

我正在尝试将文件上传到服务器。我尝试通过两种方式做到这一点。

第一种方法

这是第一种方法的代码:

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(fileName);

try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://localhost:8000/cgi-bin/test.py?action=upload&code=123");

// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);

dos.writeBytes(lineEnd);

// create a buffer of maximum size
bytesAvailable = fileInputStream.available();

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

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {

dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();

Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {

Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}

int serverResponseCode = conn.getResponseCode(); 行,代码抛出异常,如下所示:

java.io.EOFException
at libcore.io.Streams.readAsciiLine(Streams.java:203)
at libcore.net.http.HttpEngine.readHeaders(HttpEngine.java:609)
at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:562)
at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:814)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:293)
at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:505)
at ir.fajrdev.uploader.HTTP.HTTPUploader.upload1(HTTPUploader.java:241)
at ir.fajrdev.uploader.HTTP.HTTPUploader.uploadAllFiles(HTTPUploader.java:48)
at ir.fajrdev.uploader.fragments.UploadFragment$3$1.run(UploadFragment.java:74)
at java.lang.Thread.run(Thread.java:856)

我已经搜索了这个异常,这似乎是一个错误,但没有一个答案对我有用。

第二种方法

所以我尝试了另一种方法,如下所示:

File file = new File(f.address);

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://localhost:8000/cgi-bin/test.py?action=upload&code=123");

try {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

FileBody fb = new FileBody(file);
entityBuilder.addPart("file", fb);

HttpEntity entity = entityBuilder.build();

httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost, localContext);
String result = EntityUtils.toString(response.getEntity());
if ("done".equals(result)) {
DatabaseManager.sharedDB().fileUploaded(f.id);
}
} catch (IOException e) {
e.printStackTrace();
}

这里的问题是响应应该done,但它是一个空字符串。从服务器端登录后,它说没有属性文件名。服务器正在工作,因为我可以使用我之前编写的 iOS 应用程序上传文件,但我也无法在 Android 应用程序上完成此操作。

我已经检查了两种方法中发送的数据,它们看起来很相似,除了在第二个方法中,有一行 Content-Type: application/octet-stream 在第一个方法中不存在方法输出。

抱歉问了这么长的问题:)

最佳答案

 try { 

// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);

// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);

dos.writeBytes(lineEnd);

// create a buffer of maximum size
bytesAvailable = fileInputStream.available();

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

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {

dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();

Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){

runOnUiThread(new Runnable() {
public void run() {

String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;

messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {

dialog.dismiss();
ex.printStackTrace();

runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});

Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {

dialog.dismiss();
e.printStackTrace();

runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}

关于java - 从android上传文件到服务器失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29897313/

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