Android отправить файл в JSP с loopj
Мне удалось отправить файлы в JSP из HTML. HTML-код
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "UploadServel.jsp" method = "post" enctype = "multipart/form-data">
<input type = "file" name = "file" size = "50" />
<br />
Email <input name="email" id="email" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
Мой код jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import="java.sql.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.nio.file.Files" %>
<%@ page import = "java.nio.file.Paths" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
//String filePath = context.getInitParameter("file-upload");
//make dir from user_id so test will be user_id
String fileName = "";
String fieldvalue = "";
String filePath = "C://upload";
String filePath1 = "";
Files.createDirectories(Paths.get("C://upload//" ));
String dbURL = "jdbc:mysql://localhost:3306/rack";
String dbuser = "root";
String dbpassword = "";
Connection theConnection = null;
PreparedStatement theStatement = null;
System.out.println(filePath);
// Verify the content type
String contentType = request.getContentType();
System.out.println(contentType);
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
System.out.println("step 2");
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
System.out.println("step 3");
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
System.out.println("step 4");
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
System.out.println("step 5");
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
System.out.println("JSP File upload");
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
System.out.println("step 6");
if (fi.isFormField()){
String fieldname = fi.getFieldName();
System.out.println(fieldname);
fieldvalue = fi.getString();
System.out.println(fieldvalue);
Files.createDirectories(Paths.get("C://upload//" + fieldvalue));
filePath1 = "C://upload//" + fieldvalue;
System.out.println("C://upload//" + fieldvalue);
}
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
System.out.println(fieldName);
fileName = fi.getName();
System.out.println(fieldName);
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath + "//" + fileName.substring( fileName.lastIndexOf("\\"))) ;
System.out.println("1 " + fileName.substring( fileName.lastIndexOf("\\")));
} else {
file = new File( filePath + "//" + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
System.out.println("2 " + fileName.substring( fileName.lastIndexOf("\\")+1));
}
fi.write(file) ;
out.println("Uploaded Filename: " + filePath +"//" + fileName);
//insert to db fileName
}
}
Files.move(Paths.get(filePath +"//" + fileName), Paths.get(filePath1 +"//" + fileName));
String photoPath = filePath1 +"//" + fileName;
System.out.println("Copy From: " + filePath +"//" + fileName + " to " + filePath1 +"//" + fileName);
String str1 = "SELECT * FROM users ";
String str2 = "UPDATE building SET building_photo = '"+photoPath+"' where building_id='"+fieldvalue+"' ";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str1);
ResultSet theResult = theStatement.executeQuery();
if(theResult.next()){
//System.out.println("ok");
int count = theStatement.executeUpdate(str2);
}else{
}
}catch(Exception e){
System.out.println("Exception occured! "+e.getMessage()+" "+e.getStackTrace());
} finally {
try { theStatement.close(); } catch (Exception e) { /* ignored */ }
try { theConnection.close(); } catch (Exception e) { /* ignored */ }
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
}
} else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
</body>
</html>
Проблема с кодом Android, я использую loopj, но JSP-компиляция дает мне это
C://upload
multipart/form-data; boundary=-------------1496672086042
step 2
step 2
step 3
step 4
step 5
JSP File upload
и, наконец, код Android
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.io.FileNotFoundException;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
ImageView iv_result;
String name;
String dir;
String path;
String path2;
TextView tv_file;
EditText et_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_result = (ImageView) findViewById(R.id.iv_result);
Button btn_camera = (Button) findViewById(R.id.btn_camera);
Button btn_gallery = (Button) findViewById(R.id.btn_gallery);
et_name = (EditText) findViewById(R.id.et_name);
tv_file = (TextView) findViewById(R.id.tv_file);
dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
name = et_name.getText().toString();
btn_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = et_name.getText().toString();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, 0);
}
});
btn_gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);
}
});
Button send = (Button) findViewById(R.id.btn_path);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filePath = tv_file.getText().toString();
File pick = new File(filePath);
if (pick!= null) {
Log.d("path", "file created");
String url = "http://uploadFile_Android.jsp";
String boundary = "-------------" + System.currentTimeMillis();
RequestParams params = new RequestParams();
params.put("building_id", 1);
params.put("path", path2);
try {
params.put("picture", pick);
} catch (FileNotFoundException e) {
}
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("path", "success");
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace(System.out);
}
});
} else{
Log.d("path", "file don't exist");
}
}
});
}
private File getFile() {
File folder = new File("sdcard/camera_app");
if (!folder.exists()) {
folder.mkdir();
}
File image = new File(folder, name + ".jpg");
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
path = "sdcard/camera_app/" + name + ".jpg";
iv_result.setImageDrawable(Drawable.createFromPath(path));
tv_file.setText(path);
String filePath = path;
Log.d("path", "filePath:"+filePath);
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
String path1 = selectedImage.getPath();
path2 = path1 + ".jpg";
Log.d("path", path2);
iv_result.setImageURI(selectedImage);
tv_file.setText(path2);
filePath = path2;
Log.d("path", "filePath:"+filePath);
}
break;
}
}
}
активность xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.atdevelopment.takephoto.MainActivity"
android:weightSum="1">
<Button
android:id="@+id/btn_camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="camera" />
<Button
android:id="@+id/btn_galery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="galery" />
<ImageView
android:id="@+id/iv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.43" />
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="@+id/tv_file"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.07"
android:text="TextView" />
<Button
android:id="@+id/btn_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Заранее спасибо!