2 sanguine07 sanguine07 于 2013.05.22 22:20 提问

急!!!安卓程序不能上传照片到服务器

我想做一个app 实现把拍下来的照片传到服务器上,现在可以拍照并保存到手机上面,但无法上传到服务器上,是什么情况? 服务器是用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"); // 设置Content-Type字段值
            PrintWriter out2 = response.getWriter();

            // 下面的代码开始使用Commons-UploadFile组件处理上传的文件数据
            FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 分析请求,并得到上传文件的FileItem对象
            List<FileItem> items = upload.parseRequest(request);
            // 从web.xml文件中的参数中得到上传文件的路径
            String uploadPath = "d:\\cameraupload\\";
            File file = new File(uploadPath);
            if (!file.exists())
            {
                file.mkdir();
            }
            String filename = ""; // 上传文件保存到服务器的文件名
            InputStream is = null; // 当前上传文件的InputStream对象
            // 循环处理上传文件
            for (FileItem item : items)
            {
                // 处理普通的表单域
                if (item.isFormField())
                {
                    if (item.getFieldName().equals("filename"))
                    {
                        // 如果新文件不为空,将其保存在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();
            }
            // 开始上传文件
            if (!filename.equals(""))
            {
                // 用FileOutputStream打开服务端的上传文件
                FileOutputStream fos2 = new FileOutputStream(filename);
                byte[] buffer = new byte[8192]; // 每次读8K字节
                int count = 0;
                // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
                while ((count = is.read(buffer)) > 0)
                {
                    fos2.write(buffer, 0, count); // 向服务端文件写入字节流

                }
                fos2.close(); // 关闭FileOutputStream对象
                is.close(); // InputStream对象
                out2.println("文件上传成功!xii");

            }
        }
        catch (Exception e)
        {

        }
    }
}

2个回答

curie_87
curie_87   2013.05.23 13:45
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet{
  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException {
   PrintWriter out = response.getWriter();
   out.print("Request content length is " + request.getContentLength() + "<br/>"); 
   out.print("Request content type is " + request.getHeader("Content-Type") + "<br/>");
   boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   if(isMultipart){
              ServletFileUpload upload = new ServletFileUpload();
       try{
              FileItemIterator iter = upload.getItemIterator(request);
              FileItemStream item = null;
              String name = "";
              InputStream stream = null;
              while (iter.hasNext()){
                                     item = iter.next();
                                     name = item.getFieldName();
                                     stream = item.openStream();
                if(item.isFormField()){out.write("Form field " + name + ": " 
                                           + Streams.asString(stream) + "<br/>");}
                else {
                      name = item.getName();
                      if(name != null && !"".equals(name)){
                         String fileName = new File(item.getName()).getName();
                         out.write("Client file: " + item.getName() + " <br/>with file name "
                                                    + fileName + " was uploaded.<br/>");
                         File file = new File(getServletContext().getRealPath("/" + fileName));
                         FileOutputStream fos = new FileOutputStream(file);
                         long fileSize = Streams.copy(stream, fos, true);
                         out.write("Size was " + fileSize + " bytes <br/>");
                         out.write("File Path is " + file.getPath() + "<br/>");
                      }
                   }
              }
          } catch(FileUploadException fue) {out.write("fue!!!!!!!!!");}
   } 
  }
}
fyywzb
fyywzb 怎么解决的啊?????什么原因?
4 年多之前 回复
sanguine07
sanguine07 不好意思哦,,,现在才看到,,问题已经解决了 但还是非常感谢你!
4 年多之前 回复
sanguine07
sanguine07 没有什么错误提示 只是不能用
4 年多之前 回复
fyywzb
fyywzb   2013.06.25 23:35

求解决方案啊 。。。。。我跟你做的一样的代码 也是 传不到服务器报android.os.NetworkOnMainThreadException 这个错误

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!