使用 POST 将图像文件上传到 HTTP 服务器

发布于 2024-12-23 08:44:31 字数 3791 浏览 6 评论 0原文

我正在构建一个应用程序,首先需要在其上注册...注册表单外观-> 这个

它有一些必需的&一些可选字段和用户图像也是可选的。我正在服务器上发送此表单数据还上传用户图像。我遵循这个< /a> 上传用户图片&我上传用户图像的代码是 ->

public String uploadingMyImageOnServer() {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    /** path of my image */

    String pathToMyImageFile;
    if(myImagePath!=null){
     pathToMyImageFile = myImagePath; // "myImagePath" is the path which i get from gallery or from camera where image resides! 
    //Log.i("MyImagePath", pathToMyImageFile);
    }else{
          // i want to store this image when user does not provide his/her profile image
        pathToMyImageFile="/"+res.getString(R.drawable.user_logo).trim();
        Log.i("## Default pathToMyImageFile...##", "/"+res.getString(R.drawable.user_logo).trim()); // give this string -> /res/drawable/user_image.png
        }
// [----------------------------------------------------------- 
    /** my url-> To Uplopad user`s Image on php server */
    //String urlServer = "http://xxxxxxxx/yyyyy/upload_image_and.php";//Live
    String urlServer = "http://192.168.200.111/ManU/upload_image_and.php";//Local
//  -----------------------------------------------------------]

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToMyImageFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);

    outputStream.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\"" + uniqid +".png"+"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

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

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // ...Responses from the server (code and message)...
//      ResponseCache serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();



    Log.i("ImgServerrespons", serverResponseMessage);

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
    return "successfrlly";
    }
    catch (Exception ex)
    {
    //Exception handling
    }

    return "failed";
} 

当用户提供他的个人资料图片像这样时,效果很好,但如果他/她不提供个人资料那么它不会上传我从我的资源中提供的默认图像

(this->res/drawable/user_image.png)

如何在 php 服务器上上传此默认图像?

I am building one app which first require to register on it... registration form look->
this

It have some required & some optional fields and user image which is also optional. i am sending this form data on server & uploading user image as well. I follow this to upload user image & my code to upload user image is ->

public String uploadingMyImageOnServer() {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    /** path of my image */

    String pathToMyImageFile;
    if(myImagePath!=null){
     pathToMyImageFile = myImagePath; // "myImagePath" is the path which i get from gallery or from camera where image resides! 
    //Log.i("MyImagePath", pathToMyImageFile);
    }else{
          // i want to store this image when user does not provide his/her profile image
        pathToMyImageFile="/"+res.getString(R.drawable.user_logo).trim();
        Log.i("## Default pathToMyImageFile...##", "/"+res.getString(R.drawable.user_logo).trim()); // give this string -> /res/drawable/user_image.png
        }
// [----------------------------------------------------------- 
    /** my url-> To Uplopad user`s Image on php server */
    //String urlServer = "http://xxxxxxxx/yyyyy/upload_image_and.php";//Live
    String urlServer = "http://192.168.200.111/ManU/upload_image_and.php";//Local
//  -----------------------------------------------------------]

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToMyImageFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);

    outputStream.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\"" + uniqid +".png"+"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

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

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // ...Responses from the server (code and message)...
//      ResponseCache serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();



    Log.i("ImgServerrespons", serverResponseMessage);

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
    return "successfrlly";
    }
    catch (Exception ex)
    {
    //Exception handling
    }

    return "failed";
} 

when user provide his profile image like this then it works well but if he/she does not provide profile image then it does not upload the default image,

which i provide from my resources(this->res/drawable/user_image.png)

How to upload this default image on php Server ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅唱ヾ落雨殇 2024-12-30 08:44:31

嗨,我以前也遇到过这个问题,并找到了一个非常酷的解决方案。只需使用卷曲过程即可。

String[] cmd="curl --form [email protected] -m 20 http://api.face.com/faces/detect.json".split(" ");

                    ProcessBuilder pb=new ProcessBuilder(cmd);
                    p=pb.start();

                    int cur=-1;
                    InputStream in2=p.getInputStream();
                    ByteArrayOutputStream bout=new ByteArrayOutputStream();
                    cur=-1;
                    while ((cur=in2.read())!=-1) {
                        bout.write(cur);
                    }

                    String text=bout.toString();
                    System.out.println(text);

Hi ive had this problem before too and found a really cool solution. Just use a curl Process.

String[] cmd="curl --form [email protected] -m 20 http://api.face.com/faces/detect.json".split(" ");

                    ProcessBuilder pb=new ProcessBuilder(cmd);
                    p=pb.start();

                    int cur=-1;
                    InputStream in2=p.getInputStream();
                    ByteArrayOutputStream bout=new ByteArrayOutputStream();
                    cur=-1;
                    while ((cur=in2.read())!=-1) {
                        bout.write(cur);
                    }

                    String text=bout.toString();
                    System.out.println(text);
一片旧的回忆 2024-12-30 08:44:31

请尝试以下代码段,请忽略经纬度编码。它与我的项目配合得很好。

private void postImageToServer(String curURL) throws Exception
    {
        // Open up a http connection with the Web server for both send and receive operations

            midlet.get_frmLog().append("HttpConnection Enter");

            httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);

            // Set the request method to POST
            httpConnection.setRequestMethod(HttpConnection.POST);
            // Set the request headers
            httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
            httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);

            //httpConnection.setRequestProperty("lat","22.955804");
            //httpConnection.setRequestProperty("lon","72.685876");
            //httpConnection.setRequestProperty("lat",LatLonFetcherThread.getLatitude());
            //httpConnection.setRequestProperty("lon",LatLonFetcherThread.getLongitude());

            /*lat = "23.0172";
            lon = "72.3416";*/

            if ( midlet.get_choiceGroupGPS().getSelectedIndex() == 0 )
            {
                lat = LatLonFetcherThread.getLatitude();
                lon = LatLonFetcherThread.getLongitude();
            }
            else if ( midlet.get_choiceGroupGPS().getSelectedIndex() != 0 )  // Added By KALPEN
            {
                if ( midlet.state == mREPORTER.STATE_READING )
                {
                    double xLat,xLon;
                    try
                    {
                        GpsBt.instance().start();
                        //while (true)
                        {
                            gpsBt = GpsBt.instance();
                            if ( gpsBt.isConnected() )
                            {
                                location = gpsBt.getLocation();

                                //lat = location.utc;
                                //lon = location.utc;

                                lat = (location.latitude + location.northHemi);
                                lon = (location.longitude + location.eastHemi);

                                lat = lat.substring(0,lat.length()-1);
                                lon = lon.substring(0,lon.length()-1);

                                xLat = Double.parseDouble(lat) / (double)100.00;
                                xLon = Double.parseDouble(lon) / (double)100.00;

                                lat = xLat + "";
                                lon = xLon + "";

                                lat = lat.substring(0,7);
                                lon = lon.substring(0,7);

                                //lat = "23.0172";
                                //lon = "72.3416";

                            }
                            Thread.sleep(100);
                        }
                    }
                    catch  ( Exception e ) { lat = "23.0172"; lon = "72.3416"; }
                }
            }

            httpConnection.setRequestProperty("lat",lat); // Modifed by KALPEN
            httpConnection.setRequestProperty("lon",lon); // Modifed by KALPEN

            //String latlongStr = "Latitude: " + LatLonFetcherThread.getLatitude()
            //      + "\nLongitude: " + LatLonFetcherThread.getLongitude();
            /*String latlongStr = "lat: 22.955804" + "lon: 72.685876";*/

            //#style screenAlert
            /*Alert latlonAlert = new Alert("LatLon alert" );
            latlonAlert.setString(latlongStr);
            mREPORTER.display.setCurrent(latlonAlert);*/

            if(eventName == null || eventName.equals(""))
                eventName = "default";

            // all the headers are sending now and connection channel is establising
            httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
            httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
            httpConnection.setRequestProperty(ConstantCodes.COMPRESSION_MODE_REQUEST_PARAMETER, compressionMode);


            midlet.get_frmLog().append("Write on server-->"+imageBytes.length);

            DataOutputStream dos = httpConnection.openDataOutputStream();
            dos.write(imageBytes);
            midlet.threadFlag=true;
      }

kindly try following code segment, Please ignore lat-lon coding. Its work fine with my project.

private void postImageToServer(String curURL) throws Exception
    {
        // Open up a http connection with the Web server for both send and receive operations

            midlet.get_frmLog().append("HttpConnection Enter");

            httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);

            // Set the request method to POST
            httpConnection.setRequestMethod(HttpConnection.POST);
            // Set the request headers
            httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
            httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);

            //httpConnection.setRequestProperty("lat","22.955804");
            //httpConnection.setRequestProperty("lon","72.685876");
            //httpConnection.setRequestProperty("lat",LatLonFetcherThread.getLatitude());
            //httpConnection.setRequestProperty("lon",LatLonFetcherThread.getLongitude());

            /*lat = "23.0172";
            lon = "72.3416";*/

            if ( midlet.get_choiceGroupGPS().getSelectedIndex() == 0 )
            {
                lat = LatLonFetcherThread.getLatitude();
                lon = LatLonFetcherThread.getLongitude();
            }
            else if ( midlet.get_choiceGroupGPS().getSelectedIndex() != 0 )  // Added By KALPEN
            {
                if ( midlet.state == mREPORTER.STATE_READING )
                {
                    double xLat,xLon;
                    try
                    {
                        GpsBt.instance().start();
                        //while (true)
                        {
                            gpsBt = GpsBt.instance();
                            if ( gpsBt.isConnected() )
                            {
                                location = gpsBt.getLocation();

                                //lat = location.utc;
                                //lon = location.utc;

                                lat = (location.latitude + location.northHemi);
                                lon = (location.longitude + location.eastHemi);

                                lat = lat.substring(0,lat.length()-1);
                                lon = lon.substring(0,lon.length()-1);

                                xLat = Double.parseDouble(lat) / (double)100.00;
                                xLon = Double.parseDouble(lon) / (double)100.00;

                                lat = xLat + "";
                                lon = xLon + "";

                                lat = lat.substring(0,7);
                                lon = lon.substring(0,7);

                                //lat = "23.0172";
                                //lon = "72.3416";

                            }
                            Thread.sleep(100);
                        }
                    }
                    catch  ( Exception e ) { lat = "23.0172"; lon = "72.3416"; }
                }
            }

            httpConnection.setRequestProperty("lat",lat); // Modifed by KALPEN
            httpConnection.setRequestProperty("lon",lon); // Modifed by KALPEN

            //String latlongStr = "Latitude: " + LatLonFetcherThread.getLatitude()
            //      + "\nLongitude: " + LatLonFetcherThread.getLongitude();
            /*String latlongStr = "lat: 22.955804" + "lon: 72.685876";*/

            //#style screenAlert
            /*Alert latlonAlert = new Alert("LatLon alert" );
            latlonAlert.setString(latlongStr);
            mREPORTER.display.setCurrent(latlonAlert);*/

            if(eventName == null || eventName.equals(""))
                eventName = "default";

            // all the headers are sending now and connection channel is establising
            httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
            httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
            httpConnection.setRequestProperty(ConstantCodes.COMPRESSION_MODE_REQUEST_PARAMETER, compressionMode);


            midlet.get_frmLog().append("Write on server-->"+imageBytes.length);

            DataOutputStream dos = httpConnection.openDataOutputStream();
            dos.write(imageBytes);
            midlet.threadFlag=true;
      }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文