Android应用程序可以';t将照片上载到服务器

Android应用程序可以';t将照片上载到服务器,android,tomcat,Android,Tomcat,我想做一个应用程序。它可以实现将手机图片上传到服务器。现在它可以拍照并保存到手机上。但它不能上传到服务器上。如何应对?服务器正在使用tomcat进行设置 Android上传代码: import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; im

我想做一个应用程序。它可以实现将手机图片上传到服务器。现在它可以拍照并保存到手机上。但它不能上传到服务器上。如何应对?服务器正在使用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)
    {

    }
}
}
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.PrintWriter;
导入java.util.List;
导入javax.servlet.ServletException;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入org.apache.commons.fileupload.FileItem;
导入org.apache.commons.fileupload.FileItemFactory;
导入org.apache.commons.fileupload.disk.DiskFileItemFactory;
导入org.apache.commons.fileupload.servlet.ServletFileUpload;
公共类CameraServlet扩展了HttpServlet
{
受保护的无效服务(HttpServletRequest),
HttpServletResponse响应)引发ServletException,IOException
{
尝试
{
setCharacterEncoding(“UTF-8”);
setContentType(“text/html;charset=UTF-8”);
PrintWriter out2=response.getWriter();
FileItemFactory=new DiskFileItemFactory();
ServletFileUpload upload=新的ServletFileUpload(工厂);
列表项=upload.parseRequest(请求);
字符串uploadPath=“d:\\cameraupload\\”;
文件文件=新文件(上传路径);
如果(!file.exists())
{
mkdir()文件;
}
字符串filename=“”;
InputStream=null;
用于(文件项:项)
{
if(item.isFormField())
{
if(item.getFieldName().equals(“文件名”))
{
如果(!item.getString()等于(“”)
filename=item.getString(“UTF-8”);
}
}
else if(item.getName()!=null&!item.getName().equals(“”)
{
filename=item.getName().substring(
item.getName().lastIndexOf(“\\”+1);
is=item.getInputStream();//得到上传文件的输入流对象
}
}
文件名=上传路径+文件名;
if(新文件(文件名).exists())
{
新文件(文件名).delete();
}
//开始上传文件
如果(!filename.equals(“”)
{
//使用FileOutputStream在服务器中打开上载文件
FileOutputStream fos2=新的FileOutputStream(文件名);
字节[]缓冲区=新字节[8192];
整数计数=0;
//开始读取以字节为单位的上载文件,并将其输入服务器的上载文件输出流
而((count=is.read(buffer))>0)
{
write(buffer,0,count);//写入字节流服务器文件
}
fos2.close();//关闭FileOutputStream对象
is.close();//InputStream对象
out2.println(“文件上传成功!xii”);
}
}
捕获(例外e)
{
}
}
}

您有任何错误跟踪吗??我们什么都没发生

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

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

试试这个。

只需浏览和链接即可。希望这些将对您的任务有所帮助。

尝试一下……添加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());
     }

192.168.1.105不是本地网络上的IP地址吗?你确定可以通过你的电话联系到它吗?打开手机浏览器并尝试导航到URL,你能找到它吗

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

而且,每当我看到有人试图自己实现文件上传时,我都会感到痛苦。我并不是说你的代码是错误的,但与使用第三方库为你提取所有代码相比,你的代码行太多了(因此出错的风险更大)。一个著名且流行的库(如)很好地支持开箱即用的文件上载:

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
}

http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet
它没有在我这边加载。请在浏览器中查看您的问题。您真的应该回答您的问题。他们中有人帮了忙吗?