I write the code using android to write Certificate Signing Request to file .csr and store in external.
String state;
state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
{
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath()+"/MyAppFile1");
if(!dir.exists())
{
dir.mkdir();
}
File file = new File(dir,"ecc.csr");
Toast.makeText(MainActivity.this, file.getPath(), Toast.LENGTH_LONG).show();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
StringWriter writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", CSRder));
pemWriter.flush();
pemWriter.close();
String csrPEM = writer.toString();
fileOutputStream.write(csrPEM.getBytes());
fileOutputStream.close();
Toast.makeText(MainActivity.this, "SAVE", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(MainActivity.this, "NO SD CARD", Toast.LENGTH_SHORT).show();
}
And here is file path when I use toast.
Now I want to upload this .csr file to my webserver (PHP). I have to refer some guide like this (Guide 1) or (Guide 2) then write again, but it not work. I jump to Exception
Got Exception : see logcat
And log is:
6.998 20228-31551/com.example.napoleon.hocuploadfile3 E/Upload file to server Exception: Exception : /storage/emulated/0/MyAppFile1/ecc.csr (Permission denied)
java.io.FileNotFoundException: /storage/emulated/0/MyAppFile1/ecc.csr (Permission denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at com.example.napoleon.hocuploadfile3.MainActivity.upLoadFile(MainActivity.java:90)
at com.example.napoleon.hocuploadfile3.MainActivity.access$000(MainActivity.java:19)
at com.example.napoleon.hocuploadfile3.MainActivity$1$1.run(MainActivity.java:50)
at java.lang.Thread.run(Thread.java:762)
Here is my code:
final String uploadFilePath = "/storage/emulated/0/MyAppFile1/";
final String uploadFileName = "ecc.csr";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upLoadServerUri = "http://192.168.1.104/UploadToServer.php";
btnUpload = (Button) findViewById(R.id.btnUpload);
txtMessage = (TextView) findViewById(R.id.txtMessage);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this,"","Uploading...",true);
new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
txtMessage.setText("Uploading....");
}
});
upLoadFile(uploadFilePath+""+uploadFileName);
}
}).start();
}
});
}
private int upLoadFile(String sourceFileUri) {
String fileName = sourceFileUri;
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(sourceFileUri);
if(!sourceFile.isFile())
{
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
txtMessage.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
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";
txtMessage.setText(msg);
Toast.makeText(MainActivity.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() {
txtMessage.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
}
catch (Exception ex)
{
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
txtMessage.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ ex.getMessage(), ex);
}
dialog.dismiss();
return serverResponseCode;
}
}
}
I looking for help, anyway to upload file to web server.
Thanks in advance.