我正在编写一个活动来将任何类型的文件上传到服务器。
它正好检索文件名并将其分配给TextView;但是,当我选择我的上传按钮时,它很快就会给我一个“源文件不存在”错误,并且不会将文件上传到我的服务器。(PHP代码工作正常,因为我在其他地方使用过它)
我认为问题在于OnActivityResult中的uploadFilePath变量。我不知道为什么。任何帮助表示赞赏。感谢。
上传电话:
private void uploadFile(final String media_id) {
class UploadFile extends AsyncTask<Void, Void, String> {
ProgressDialog uploading;
@Override
protected void onPreExecute() {
super.onPreExecute();
uploading = ProgressDialog.show(FileUpload.this, "Uploading File", "Please wait...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
uploading.dismiss();
finish();
Toast.makeText(getApplicationContext(), "File uploaded successfully.", Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
String filepath = uploadFilePath;
String msg = uploadFile(filepath, media_id);
return msg;
}
}
UploadFile uv = new UploadFile();
uv.execute();
}
上传代码:
public String uploadFile(String file, final String id) {
String fileName = file;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(file);
if (!sourceFile.isFile()) {
Log.e("Error", "Source File Does not exist");
return null;
}
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(UPLOAD_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("myFile", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
//Adding Parameter name
dos.writeBytes("Content-Disposition: form-data; name=\"media_id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(media_id); // mobile_no is String variable
dos.writeBytes(lineEnd);
//Adding Parameter filepath
dos.writeBytes(twoHyphens + boundary + lineEnd);
String filepath="url"+fileName;
dos.writeBytes("Content-Disposition: form-data; name=\"filepath\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(filepath); // mobile_no is String vaiable
dos.writeBytes(lineEnd);
//Adding Media File Parameter
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.i("Result", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException ioex) {
}
return sb.toString();
}else {
return "Could not upload";
}
}
OnActivityResult代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == REQUEST_CODE_DOC) {
if (resultCode == RESULT_OK) {
// Get the Image from data
Uri selectedFilePath = data.getData();
String uriString = selectedFilePath.toString();
File fileToUpload = new File(uriString);
uploadFilePath = fileToUpload.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedFilePath, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
uploadFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
filename.setText(uploadFileName);
uploadFile.setVisibility(View.VISIBLE);
mEditText.setVisibility(View.VISIBLE);
mSplashImage.setVisibility(View.INVISIBLE);
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
uploadFileName = fileToUpload.getName();
filename.setText(uploadFileName);
uploadFile.setVisibility(View.VISIBLE);
mEditText.setVisibility(View.VISIBLE);
mSplashImage.setVisibility(View.INVISIBLE);
}else {
filename.setText("Invalid file type");
}
}else if (resultCode == RESULT_CANCELED){
Toast.makeText(this, "User Canceled File Request.", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "File Request failed.", Toast.LENGTH_LONG).show();
}
} else{
Toast.makeText(this, "Error loading File. Please try again.", Toast.LENGTH_LONG).show();
}
}
UPLOAD_URL:
if (isset($_POST['media_id']) && isset($_POST['file'])) {
// receiving the post params
$media_id = $_POST['media_id'];
$filepath = $_POST['file'];
if ($filepath != null){
$file_path = "uploads/$media_id.pdf";
$file = $_FILES['myFile']['name'];
$file_tmp = $_FILES['myFile']['tmp_name'];
$user = $db->storeFile($filepath, $media_id);
move_uploaded_file($file_tmp, $file_path);
$user = $db->storeFile($filepath, $media_id);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["file"]["media_id"] = $user["media_id"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in upload!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Error uploading file.";
echo json_encode($response);
}
?>
storeFile函数:
public function storeFile($file, $media_id) {
$filename = "***.com/uploads/$media_id.pdf";
$stmt = $this->conn->prepare("UPDATE files SET file=? WHERE media_id=?");
$stmt->bind_param("ss", $filename, $media_id);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT media_id FROM files WHERE media_id = ?");
$stmt->bind_param("s", $media_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}