嗨,我正在为我的实习制作一个应用程序,但我收到了一个错误。
请帮我解决这个问题
这是myactivity.java
private String SERVER_URL = "http://rarefactive-perfora.000webhostapp.com/crmobile/upload.php";
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intents
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.DateImp){
datePickerDialog.show();
}
if(view.getId()==R.id.select){
showFileChooser();
}
if (view.getId()==R.id.b_upload){
if (selectedFilePath != null){
Toast.makeText(getApplicationContext(),"Success upload file", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
uploadFile(selectedFilePath);
}
}).start();
}else{
Toast.makeText(getApplicationContext(),"Please choose a file first", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == REQUEST_TAKE_PHOTO) {
Uri uri = Uri.fromFile(photoFile); // Here photo file is the file EXTRA_OUTPUT location where you saved the actual camera image
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
selectedFilePath = FilePath.getPath(this, uri);
Log.i(TAG,"Selected File Path:"+selectedFilePath);
if (selectedFilePath != null && !selectedFilePath.equals("")){
tv_file_name.setText(selectedFilePath);
}else{
Toast.makeText(this, "Cannot upload file to server", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resultCode == Activity.RESULT_OK){
if (requestCode == PICK_FILE_REQUEST){
if (data == null){
return;
}
Bitmap bitmap1;
Uri selectedFileUri = data.getData();
try {
bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedFileUri);
imageView.setImageBitmap(bitmap1);
selectedFilePath = FilePath.getPath(this, selectedFileUri);
Log.i(TAG,"Selected File Path:"+selectedFilePath);
if (selectedFilePath != null && !selectedFilePath.equals("")){
tv_file_name.setText(selectedFilePath);
}else{
Toast.makeText(this, "Cannot upload file to server", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public int uploadFile(final String selectedFilePath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_file_name.setText("Source file doesn't exist: "+selectedFilePath);
}
});
return 0;
}else{
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("upload_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"upload_file\";filename=\"" + selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_file_name.setText(fileName);
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
return serverResponseCode;
}
}
Submit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
final int PnT = PnTenv.getCheckedRadioButtonId();
final int CnF = CnFlist.getCheckedRadioButtonId();
if (){
//my validation
}else{
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setTitle("Message!");
alertBuilder
.setMessage("Do you really want to Submit this Request?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
final String PnTe = ((RadioButton) findViewById(PnT)).getText().toString();
final String CnFl = ((RadioButton) findViewById(CnF)).getText().toString();
Intent i = getIntent();
String cr_no = i.getStringExtra("cr_no");
String npk = i.getStringExtra("npk");
String cr_title = i.getStringExtra("cr_title");
String it_care_tick = i.getStringExtra("it_care_ticket");
String req_source = i.getStringExtra("request_source");
String req_type = i.getStringExtra("request_type");
String cr_date_req = i.getStringExtra("cr_date_req");
String brief_desc = i.getStringExtra("brief_desc");
String reason = i.getStringExtra("reason");
String sev_lvl = i.getStringExtra("severity_lvl");
String remark = i.getStringExtra("remark");
status.setText("Waiting for Supervisor");
RequestActivity2.InsertReq2 insertReq2 = new RequestActivity2.InsertReq2();
insertReq2.execute(cr_no, npk, cr_title, it_care_tick, req_source, req_type, cr_date_req, brief_desc, reason, sev_lvl, remark, DateImp.getText().toString(), HourI.getText().toString(), TimeI.getText().toString(), SystemI.getText().toString(), ScopeI.getText().toString(), ChangeObj.getText().toString(), PnTe, CnFl, checklist.getText().toString(), fallback.getText().toString(), tv_file_name.getText().toString(), status.getText().toString());
startActivity(new Intent(getApplicationContext(), crRequestor.class));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}
}
});
}
private class InsertReq2 extends AsyncTask<String, String, JSONObject>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... args) {
String cr_no = args[0];
String npk = args[1];
String cr_title = args[2];
String it_care_ticket = args[3];
String request_source = args[4];
String request_type = args[5];
String cr_date_req = args[6];
String brief_desc = args[7];
String reason = args[8];
String severity_lvl = args[9];
String remark = args[10];
String date_impact = args[11];
String hour_impact = args[12];
String time_impact = args[13];
String system_impact = args[14];
String scope_impact = args[15];
String change_objective = args[16];
String testing_piloting = args[17];
String checklist_fallback = args[18];
String checklist = args[19];
String fallback = args[20];
String upload_file = args[21];
String status = args[22];
ArrayList params = new ArrayList();
params.add(new BasicNameValuePair("cr_no", cr_no));
params.add(new BasicNameValuePair("npk", npk));
params.add(new BasicNameValuePair("cr_title", cr_title));
params.add(new BasicNameValuePair("it_care_ticket", it_care_ticket));
params.add(new BasicNameValuePair("request_source", request_source));
params.add(new BasicNameValuePair("request_type", request_type));
params.add(new BasicNameValuePair("cr_date_req", cr_date_req));
params.add(new BasicNameValuePair("brief_desc", brief_desc));
params.add(new BasicNameValuePair("reason", reason));
params.add(new BasicNameValuePair("severity_lvl", severity_lvl));
params.add(new BasicNameValuePair("remark", remark));
params.add(new BasicNameValuePair("date_impact", date_impact));
params.add(new BasicNameValuePair("hour_impact", hour_impact));
params.add(new BasicNameValuePair("time_impact", time_impact));
params.add(new BasicNameValuePair("system_impact", system_impact));
params.add(new BasicNameValuePair("scope_impact", scope_impact));
params.add(new BasicNameValuePair("change_objective", change_objective));
params.add(new BasicNameValuePair("testing_piloting", testing_piloting));
params.add(new BasicNameValuePair("checklist_fallback", checklist_fallback));
params.add(new BasicNameValuePair("checklist", checklist));
params.add(new BasicNameValuePair("fallback", fallback));
params.add(new BasicNameValuePair("upload_file", upload_file));
params.add(new BasicNameValuePair("status", status));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这是upload.php
<?php
$file_path = "uploads/";
$file_path = $file_path.basename($_FILES['upload_file']['name']);
if(move_uploaded_file($_FILES['upload_file']['tmp_name'], $file_path)){
$result = array("result" => "success");
}else{
$result = array("result" => "failed");
}
echo json_encode($result);
?>
这是我的phpmyadmin输出:/storage/emulated/0/Android/data/com.example.user.appname/files/Pictures/JPEG_20170918_803639971.jpg
我希望我的输出是JPEG_20170918_803639971.jpg
请帮我解决这个问题。