java - 将文件(图像)从 Android 设备发送到使用 REST 编写的服务器上的 Web 服务

标签 java android web-services rest

我想将图像从 Android 设备发送到在 Tomcat 服务器上运行的 Web 应用程序。请帮助我编写一些小代码,用于将图像发送到在 Web 服务器上运行的 REST Web 服务。如果可能,请向我提供示例代码。我很困惑该使用什么方法。任何帮助将不胜感激。提前致谢。

编辑:这个问题的答案如下

while(it.hasNext()){
             File file = new File((new StringBuilder()).append(Environment.getExternalStorageDirectory()).append(File.separator).append("jcms").append(File.separator).append("Customer_").append( customer.getId()).toString());
             File[] listOfFiles = file.listFiles(); 

             for(int i=0;i<listOfFiles.length;i++){
                 JSONObject message = new JSONObject();
                 File fil=listOfFiles[i];
                 FileInputStream imageInFile = new FileInputStream(fil);
                 byte imageData[] = new byte[(int)fil.length()];
                 imageInFile.read(imageData);
                 String imageDataString = encodeImage(imageData);



                 URL url=new URL(ClearCustomersContract.CLEAR_SERVER_URL);
                 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                 connection.setDoOutput(true);
                 connection.setRequestProperty("Content-Type", "application/json");
                 connection.setRequestMethod("POST");
                 connection.setConnectTimeout(5000);
                 connection.setReadTimeout(5000);
                 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
                 out.write(imageDataString);
                 out.close();

                 BufferedReader in = new BufferedReader(new InputStreamReader(
                         connection.getInputStream()));
                 while (in.readLine() != null) {
                 }
                 in.close();    
             }
        }

服务器端的 REST Web 服务就像

@Override
@POST
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_OCTET_STREAM})
@Path("/getData")
public Response getAllTheSyncData(InputStream incomingData) {
    StringBuilder sb = new StringBuilder();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
        String line = null;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
    } catch (Exception e) {
        System.out.println("Error Parsing: - ");
    }
    return Response.status(200).entity("Success").build();
}

这就是我们将字符串转换回图像的方法。

byte[] imageByteArray =decodeImage(jsonObj.get("imageData").toString());

               imageOutFile = new FileOutputStream(
                        "C:/Users/SUNILKUMAR/Desktop/result.jpg");

            // Write a image byte array into file system

            imageOutFile.write(imageByteArray);


            imageOutFile.close();

最佳答案

检查link 。它给出了如何将文件上传到服务器的完整示例。

或检查下面的代码 -

public class HttpFileUpload implements Runnable{
    URL connectURL;
    String responseString;
    String Title;
    String Description;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;

    HttpFileUpload(String urlString, String vTitle, String vDesc){
            try{
                    connectURL = new URL(urlString);
                    Title= vTitle;
                    Description = vDesc;
            }catch(Exception ex){
                Log.i("HttpFileUpload","URL Malformatted");
            }
    }

    void Send_Now(FileInputStream fStream){
            fileInputStream = fStream;
            Sending();
    }

    void Sending(){
            String iFileName = "ovicam_temp_vid.mp4";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            String Tag="fSnd";
            try
            {
                    Log.e(Tag,"Starting Http File Sending to URL");

                    // Open a HTTP connection to the URL
                    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                    // Allow Inputs
                    conn.setDoInput(true);

                    // Allow Outputs
                    conn.setDoOutput(true);

                    // Don't use a cached copy.
                    conn.setUseCaches(false);

                    // Use a post method.
                    conn.setRequestMethod("POST");

                    conn.setRequestProperty("Connection", "Keep-Alive");

                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(Title);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(Description);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                    dos.writeBytes(lineEnd);

                    Log.e(Tag,"Headers are written");

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

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

                    // read file and write it into form...
                    int 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);
                    }
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    // close streams
                    fileInputStream.close();

                    dos.flush();

                    Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                    InputStream is = conn.getInputStream();

                    // retrieve the response from server
                    int ch;

                    StringBuffer b =new StringBuffer();
                    while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                    String s=b.toString();
                    Log.i("Response",s);
                    dos.close();
            }
            catch (MalformedURLException ex)
            {
                    Log.e(Tag, "URL error: " + ex.getMessage(), ex);
            }

            catch (IOException ioe)
            {
                    Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
            }
    }

    @Override
    public void run() {
            // TODO Auto-generated method stub
    }
  }

public void UploadFile(){
  try {
  // Set your file path here
  FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");

 // Set your server page url (and the file title/description)
 HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");

 hfu.Send_Now(fstrm);

  } catch (FileNotFoundException e) {
    // Error: File not found
 }
 }

关于java - 将文件(图像)从 Android 设备发送到使用 REST 编写的服务器上的 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29002596/

相关文章:

java - 当JFrame不断重绘时如何设置形状的渐变?

使用 AppCompat 时,Android 的 splitActionBarWhenNarrow 在 Gingerbread 中不起作用

android - Android 上的 _vscprintf 等效?

javascript - 从 asp.net 中的 Web 服务绑定(bind)失败

java - 使用 Web 服务和 2 路 SSL

java - Java参数引用和原始引用(不是对象)如何相同?

java - Java中使用Random.nextInt对数组进行两次洗牌

c# - 如何在.net中的Web服务中调度[WebMethod]?

java - 我需要在 arraylist 中找到一个整数数据?

android - 如何在 Android 中制作秒表?