我想将选定的用户图像上传到服务器,但是当我上传时,我得到IOException
这是我的代码:
String Sending(List<String> MyParams, List<String> MyParamsValue) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag = "fSnd";
try {
Log.e(Tag, "Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
// ////////////////////////////////////////////////////////////////////
conn.setRequestProperty("User-Agent", ctx.getResources().getString(com.pnp.divanEhafez.R.string.app_name));
// ////////////////////////////////////////////////////////////////////
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
for (int o = 0; o < MyParams.size(); o++) {
if (MyParamsValue.get(o).trim().length() >= 1) {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + MyParams.get(o).toString() + "\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.write(MyParamsValue.get(o).getBytes("UTF-8"));
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
}
}
for (int f = 0; f < fileInputStream.size(); f++) {
// if (f == 0)
// dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
// + "thumb.jpg"
// + "\"" + lineEnd);
// else
String FileName = MediaListName.get(f).substring(MediaListName.get(f).lastIndexOf("/") + 1);
System.out.println(FileName);
dos.writeBytes("Content-Disposition: form-data; name=\"tfile" + String.valueOf(f) + "\";filename=\""
+ FileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.get(f).available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.get(f).read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.get(f).available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.get(f).read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
if ((f + 1) < fileInputStream.size())
dos.writeBytes(twoHyphens + boundary + lineEnd);
else
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.get(f).close();
}
dos.close();
Log.e(Tag, "File Sent, Response: " + String.valueOf(conn.getResponseCode()));
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = reader.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
dos.close();
conn.disconnect();
return s;
} catch (MalformedURLException ex) {
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
TrackHelper.trackFatalException(ctx, ex);
} catch (IOException ioe) {
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
TrackHelper.trackFatalException(ctx, ioe);
}
return "";
}
和我的错误LogCat:
2019-07-01 21:52:14.007 24031-25093 / com.pnp.divanEhafez E / fSnd: 启动Http文件发送到URL 2019-07-01 21:52:14.056 24031-25093 / com.pnp.divanEhafez E / fSnd:标头写在2019-07-01 21:52:14.534 24031-25093 / com.pnp.divanEhafez E / fSnd:已发送文件, 响应:500 2019-07-01 21:52:14.537 24031-25093 / com.pnp.divanEhafez E / fSnd:IO错误:http://myURL/?option=webservicehafezop java.io.FileNotFoundException:http://myURL 在com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250) 在com.pnp.divanEhafez.Network.HttpFileUpload.Sending(HttpFileUpload.java:146) 在com.pnp.divanEhafez.Network.HttpFileUpload.Send_Now(HttpFileUpload.java:50) 在com.pnp.divanEhafez.UserAccount $ 3.run(UserAccount.java:181) 在java.lang.Thread.run(Thread.java:761)
答案 0 :(得分:0)
我建议您设置文件提供者,因为以上Lolipop版本需要文件提供者才能访问文件系统,这是代码:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.package.name.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
在res目录中创建一个xml文件夹。 在其中添加provider_paths.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
现在编写Java代码以从存储中获取文件:
private String getImageFromFilePath(Intent data) {
boolean isCamera = data == null || data.getData() == null;
if (isCamera) return getCaptureImageOutputUri().getPath();
else return getPathFromURI(data.getData());
}
public String getImageFilePath(Intent data) {
return getImageFromFilePath(data);
}
private String getPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Audio.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}