Android应用程序无法将照片上传到服务器

时间:2013-05-23 05:31:03

标签: android tomcat

我想做一个应用程序。它可以实现将手机图片上传到服务器。现在它可以拍照并保存到手机上。但它无法上传到服务器。怎么处理这个?服务器正在使用tomcat进行设置。

Android上传代码:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class uploadActivity extends Activity
{
private Button uploadbutton;
private String uploadFile = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String srcPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String actionUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
uploadbutton=(Button)findViewById(R.id.button2);
uploadbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
    }
 private void uploadFile()
  { String uploadUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet";
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";
    try
    {
      URL url = new URL(uploadUrl);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url
          .openConnection();
      httpURLConnection.setDoInput(true);
      httpURLConnection.setDoOutput(true);
      httpURLConnection.setUseCaches(false);
      httpURLConnection.setRequestMethod("POST");
      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
      httpURLConnection.setRequestProperty("Charset", "UTF-8");
      httpURLConnection.setRequestProperty("Content-Type",
          "multipart/form-data;boundary=" + boundary);
      DataOutputStream dos = new DataOutputStream(httpURLConnection
          .getOutputStream());
      dos.writeBytes(twoHyphens + boundary + end);
      dos
          .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
              + srcPath.substring(srcPath.lastIndexOf("/") + 1)
              + "\"" + end);
      dos.writeBytes(end);
      FileInputStream fis = new FileInputStream(srcPath); 
      byte[] buffer = new byte[8192]; // 8k
      int count = 0;
      while ((count = fis.read(buffer)) != -1)
      {
        dos.write(buffer, 0, count);
      }
      fis.close();
      dos.writeBytes(end);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      dos.flush();
      InputStream is = httpURLConnection.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      String result = br.readLine();
      Toast.makeText(this, result, Toast.LENGTH_LONG).show();//
      dos.close();
      is.close();
    } catch (Exception e)
    {
      e.printStackTrace();
      setTitle(e.getMessage());
    }
  }
}

服务器代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CameraServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
request.setCharacterEncoding("UTF-8"); 
response.setContentType("text/html;charset=UTF-8"); 
PrintWriter out2 = response.getWriter();

        FileItemFactory factory = new DiskFileItemFactory(); 
        ServletFileUpload upload = new ServletFileUpload(factory);        
        List<FileItem> items = upload.parseRequest(request);
         String uploadPath = "d:\\cameraupload\\";
        File file = new File(uploadPath);
        if (!file.exists())
        {
            file.mkdir();
        }
        String filename = ""; 
        InputStream is = null; 
                for (FileItem item : items)
        {

            if (item.isFormField())
            {
                if (item.getFieldName().equals("filename"))
                {
                                        if (!item.getString().equals(""))
                        filename = item.getString("UTF-8");
                }
            }
                        else if (item.getName() != null && !item.getName().equals(""))
            {
                              filename = item.getName().substring(
                        item.getName().lastIndexOf("\\") + 1);
                is = item.getInputStream(); // 得到上传文件的InputStream对象
            }
        }
               filename = uploadPath + filename;
                if (new File(filename).exists())
        {
            new File(filename).delete();
        }
        // Began to upload files
        if (!filename.equals(""))
        {
            // use FileOutputStream to open the upload file in server
            FileOutputStream fos2 = new FileOutputStream(filename);
            byte[] buffer = new byte[8192]; 
            int count = 0;
            // Began to read the upload file in bytes,and input it to server's upload file output stream
            while ((count = is.read(buffer)) > 0)
            {
                fos2.write(buffer, 0, count); // To write the byte stream server files
            }
            fos2.close(); // close FileOutputStream object
            is.close(); // InputStream object
            out2.println("file upload success!xii");

        }
    }
    catch (Exception e)
    {

    }
}
}

4 个答案:

答案 0 :(得分:0)

你有任何错误追踪?我们什么都没发生?

要使用httpurlconnection,您需要在开头更改策略:

ThreadPolicy mThreadPolicy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(mThreadPolicy);

试试这个。

答案 1 :(得分:0)

只需浏览thisthis个链接即可。希望这些对你的任务有所帮助。

答案 2 :(得分:0)

试试这个...添加apache-mime4j-0.6.jar和httpmime-4.0.3.jar libs

      File f=new File(exsistingFileName);
      HttpClient http = new DefaultHttpClient();
 HttpPost post = new HttpPost("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet");
 MultipartEntity Mentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String url1=exsistingFileName;
 String mime;

    String extension = MimeTypeMap.getFileExtensionFromUrl(url1);
    if (extension != ""&&extension!=null) {
        MimeTypeMap mime1 = MimeTypeMap.getSingleton();
        mime = mime1.getMimeTypeFromExtension(extension);
    }
    else
    {
            String ext = url1.substring((url1.lastIndexOf(".") + 1), url1.length());
            MimeTypeMap mime1 = MimeTypeMap.getSingleton();
            mime = mime1.getMimeTypeFromExtension(ext);
    }


 ContentBody cbFile;
 if(mime!=null)
     cbFile= new FileBody(f,mime);
 else
     cbFile=new FileBody(f);
 Mentity.addPart("file",cbFile);
post.setEntity(Mentity);
 HttpResponse response = null;
try {
    response = http.execute(post);
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

try {
    responseString = new BasicResponseHandler().
       handleResponse(response);
} catch (HttpResponseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

     HttpEntity entity = response.getEntity();

     System.out.println("----------------------------------------");
     System.out.println(response.getStatusLine());
     if (entity != null) {
         System.out.println("Response content length: " + entity.getContentLength());
     }

答案 3 :(得分:0)

本地网络上的IP地址不是192.168.1.105吗?你确定它可以通过手机访问吗?打开手机的浏览器并尝试导航到该网址,是否可以访问该网址?

您在上传时遇到问题?客户端或服务器?如果它在客户端上,你会得到什么错误?还是它默默地失败了?您是否尝试制作一个简单的HTML表单并从那里进行上传?如果这有效,你知道这是你的Android代码问题吗?

此外,每当我看到有人试图自己实现文件上传时,它就会受到伤害。我不是说你的代码是错误的,但与你使用第三方库为你抽象掉所有代码相比,这是一大堆代码(因此存在更多的错误风险)。一个众所周知且受欢迎的库,例如Android Asynchronous Http Client,可以很好地支持开箱即用的文件上传:

AsyncHttpClient client = new AsyncHttpClient();
String filename = "file.png";
File myFile = new File("/path/to/" + filename);
RequestParams params = new RequestParams();
try {
    params.put("file", myFile);
    params.put("filename", filename);
    client.post("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet", params, responseHandler);
}
catch(FileNotFoundException e) {
    // handle
}