无法在服务器上上传图像文件

时间:2015-04-02 05:40:17

标签: android image-uploading image-upload image-file

我正在尝试在服务器上传图片。当我点击上传按钮时,我得到响应代码200即可。但是,然后我检查IIS上用于检查上传图像的文件夹,它显示空文件夹。简单地说,没有上传的文件。我不知道自己哪里出错了。这是我的代码,

new Upload().execute();

    class Upload extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
              String upLoadServerUri = "http://192.168.77.120/CheckInn/Reservation.svc/Upload";
              String fileName = "/storage/extSdCard/DCIM/Camera/images.jpeg";

              HttpURLConnection conn = null;
              DataOutputStream dos = null;  
              String lineEnd = "\r\n";
              String twoHyphens = "--";
              String boundary = "*****";
              int bytesRead, bytesAvailable, bufferSize;
              byte[] buffer;
              int maxBufferSize = 1 * 1024 * 1024; 
              File sourceFile = new File("/storage/extSdCard/DCIM/Camera/images.jpeg"); 
              if (!sourceFile.isFile()) {
               Log.e("uploadFile", "Source File Does not exist");
//             return 0;
              }
                  try { // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);
                   conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("uploaded_file", fileName); 
                   dos = new DataOutputStream(conn.getOutputStream());
         System.out.println("..........");
                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
                   dos.writeBytes(lineEnd);

                   bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   buffer = new byte[bufferSize];

                   // read file and write it into form...
                   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);               
                    }

                   // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                   // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseMessage();
                   System.out.println("....." + serverResponseCode);
                   String serverResponseMessage = conn.getResponseMessage();

                   Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
                   if(!serverResponseMessage.isEmpty()){
                       runOnUiThread(new Runnable() {
                            public void run() {
                                tv.setText("File Upload Completed.");
                                Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {  
                  dialog.dismiss();  
                  ex.printStackTrace();
                  Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {
                  dialog.dismiss();  
                  e.printStackTrace();
                  Toast.makeText(MainActivity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                  Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
              }
              dialog.dismiss();     
            return null;
        }

    }

网络服务代码:

public string Upload(Stream Uploading)
        {
            MultipartParser parser = new MultipartParser(Uploading);
            string fullOutputPath = @"E:\Publish\CheckIn\Documents\" + parser.Filename;// + ".jpg";
            if (parser.Success)
            {
                byte[] imgByte = parser.FileContents;
                System.Drawing.Image img;
                using (MemoryStream memStream = new MemoryStream(imgByte))
                {
                    using (img = System.Drawing.Image.FromStream(memStream))
                    {
                        img.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                // Save the file
                // SaveFile(parser.Filename, parser.ContentType, parser.FileContents);
            }
            return "File Save Successfully";
}

1 个答案:

答案 0 :(得分:0)

尝试以下代码,它适用于我

public static String submitData()
{
    String m_wsUrl = "http://192.168.77.120/CheckInn/Reservation.svc/Upload";
    String m_filePath = "/storage/extSdCard/DCIM/Camera/images.jpeg";
    String m_fileKey = "uploaded_file";
    String m_serverResponse = null;
    try
    {
        HttpURLConnection m_httpconnection = null;
        String m_attachment_type;
        OutputStream m_outputStream;
        m_httpconnection = (HttpURLConnection) new URL(m_wsUrl).openConnection();
        m_httpconnection.setConnectTimeout(5000);
        m_httpconnection.setDoInput(true);
        m_httpconnection.setDoOutput(true);
        m_httpconnection.setRequestMethod("POST");
        m_httpconnection.setRequestProperty("Connection", "Keep-Alive");
        m_httpconnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
        m_attachment_type = "application/octet-stream";
        m_outputStream = m_httpconnection.getOutputStream();
        StringBuffer m_buffer = new StringBuffer();
        m_buffer.append("--" + BOUNDARY + "\r\n");
        m_buffer.append("Content-Disposition: form-data; name=\"webdata\"" + "\r\n\r\n");
        m_outputStream.write(m_buffer.toString().getBytes());
        if (m_filePath != null)
        {
            String m_str = "--" + BOUNDARY + "\r\n" + "Content-Disposition: form-data; name=" + m_fileKey + "; filename=\"" + new File(m_filePath).getName() + "\"\r\n" + "Content-Type: " + m_attachment_type + "\r\n" + "\r\n";
            m_outputStream.write(m_str.getBytes());
            byte[] m_mediaNuffer = new byte[BUFFER_SIZE];
            try
            {
                m_in = new BufferedInputStream(new FileInputStream(m_filePath));
                while ((m_in.read(m_mediaNuffer, 0, BUFFER_SIZE)) > 0)
                {
                    m_outputStream.write(m_mediaNuffer);
                }
            }
            catch (Exception p_e)
            {
            }
            finally
            { // always close input stream
                try
                {
                    m_in.close();
                }
                catch (IOException p_e)
                {
                }
            }
            m_outputStream.write("\r\n".getBytes());
            m_outputStream.write(("--" + BOUNDARY + "\r\n").getBytes());
        }
        m_outputStream.flush();
        m_outputStream.close();
        if (m_httpconnection.getResponseCode() == HttpURLConnection.HTTP_OK)
        {
            try
            {
                String m_str;
                StringBuffer m_buff = new StringBuffer();
                BufferedReader m_in = new BufferedReader(new InputStreamReader(m_httpconnection.getInputStream()));
                while ((m_str = m_in.readLine()) != null)
                    m_buff.append(m_str);
                m_serverResponse = m_buff.toString();
                return m_serverResponse;
            }
            catch (IOException p_te)
            {
                // UNABLE_TO_CONNECT_SERVER
            }
            finally
            {
                try
                {
                    m_httpconnection.disconnect();
                }
                catch (Throwable p_e)
                {
                }
            }
        }
        else
        {
            // UNABLE_TO_CONNECT_SERVER
        }
    }
    catch (SocketTimeoutException te)
    {
    }
    catch (IOException ie)
    {
    }
    return m_serverResponse;
}