Java 将图像以多部分形式上传到android服务器而无需更改
在我的应用程序中,我试图在grails服务器上上传一个图像,问题是将图像转换为Base64格式在后端不被接受,服务器开发人员说它不应该是多部分格式。这是我的密码:Java 将图像以多部分形式上传到android服务器而无需更改,java,android,Java,Android,在我的应用程序中,我试图在grails服务器上上传一个图像,问题是将图像转换为Base64格式在后端不被接受,服务器开发人员说它不应该是多部分格式。这是我的密码: ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); Bitmap bitmap = BitmapFactory.decodeFile(imagePath); B
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr,Base64.DEFAULT);
nameValuePairs.add(new BasicNameValuePair("fileupload",image_str));
nameValuePairs.add(new BasicNameValuePair("message", "trial"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serverURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i(TAG, " http reponse is:" +response);
convertResponseToString(response);
}catch(Exception e){
System.out.println("Error in http connection "+e.toString());
}
main.xml
AndroidManifest.xml
upload.php
我建议您使用Multipartentity示例如下:
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(YOUR_URL_HERE);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if (Photo != null) {
mpEntity.addPart("photo", new ByteArrayBody(Photo,
"YOURPHOTO.png"));
}
try {
if (Photo != null) {
myConnection.setEntity(mpEntity);
}
response = myClient.execute(myConnection);
}
catch (Exception e) {
result.setResult(BaseID.REQUEST_DATA_MEMBER_CREATE_FAILED);
result.setError_title("Exeption Title");
result.setError_message("Exeption Messege");
e.printStackTrace();
}
我希望您能理解我的答案,如果您对我的答案有任何疑问,请随时在评论中提问:我是否需要添加任何jar文件,因为它显示MultipartEntity mpEntity=new MultipartEntity HttpMultipartMode.BROWSER\u COMPATIBLE上未解析的实体;这一行本身。@user1472202啊,是的,我忘了提到你需要从这里下载httpmime-4.2.2.jar。你有java服务器端代码的例子吗。我的意思是我们可以用java来代替php。
public class uploadfile extends Activity {
TextView tv = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
doFileUpload();
}
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/six.3gp";
// Is this the place are you doing something wrong.
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://192.168.1.5/upload.php";
try
{
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
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("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
bytesAvailable = fileInputStream.available();
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);
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
tv.append(inputLine);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
/*while((str = inStream.readLine()) !=null ){
}*/
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
}
<uses-permission android:name="android.permission.INTERNET" />
<?php
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./".$_FILES["uploadedfile"]["name"]);
?>
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(YOUR_URL_HERE);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if (Photo != null) {
mpEntity.addPart("photo", new ByteArrayBody(Photo,
"YOURPHOTO.png"));
}
try {
if (Photo != null) {
myConnection.setEntity(mpEntity);
}
response = myClient.execute(myConnection);
}
catch (Exception e) {
result.setResult(BaseID.REQUEST_DATA_MEMBER_CREATE_FAILED);
result.setError_title("Exeption Title");
result.setError_message("Exeption Messege");
e.printStackTrace();
}