1

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

安卓上传代码:

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

4 回答 4

0

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

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

此外,每次我看到有人试图自己实现文件上传时,都会很痛苦。我并不是说您的代码是错误的,但与您使用 3rd 方库为您抽象出所有代码相比,它的代码行数非常多(因此出错的风险更大)。一个众所周知且流行的库,例如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
}
于 2013-05-23T05:49:28.527 回答
0

只需通过这个这个链接。希望这些对您的任务有所帮助。

于 2013-05-23T05:38:20.153 回答
0

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

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

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

尝试这个。

于 2013-05-23T05:35:49.910 回答
0

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

      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());
     }
于 2013-05-23T05:46:20.303 回答