使用HTTPURLConnection从Android上传文件到node.js服务器

时间:2016-04-28 08:26:33

标签: javascript android node.js

如果有人可以帮我指导我究竟做错了什么..因为我使用Postman客户端向我的node.js服务器发出get请求并且能够完美地完成它细

04-28 01:21:03.983 5362-5486/xyz.hexene.localvpn I/uploadFile: HTTP Response is : Not Found: 404
04-28 01:21:03.983 5362-5486/xyz.hexene.localvpn E/404 ERROR: Not Found

这是我的android代码:

   public void uploadFile() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            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(AccountInfo.getContext().getFilesDir() + "/" + fileName);

            if (!sourceFile.isFile()) {
                Log.e("uploadFile", "Source File not exist :" + AccountInfo.getContext().getFilesDir() + "/" + fileName);
            } else {
                try {

                    FileInputStream fileInputStream = new FileInputStream(sourceFile);
                    URL url = new URL("http://192.168.1.66:3000/upload");
                    conn = (HttpURLConnection) url.openConnection();
                    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());


                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    //Adding Parameter name

                    String name = "amir";
                    dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd);
                    //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                    //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(name); // mobile_no is String variable
                    dos.writeBytes(lineEnd);

                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    //Adding Parameter phone
                    String phone = "9956565656";
                    dos.writeBytes("Content-Disposition: form-data; name=\"phone\"" + lineEnd);
                    //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                    //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(phone); // mobile_no is String variable
                    dos.writeBytes(lineEnd);


                    //Json_Encoder encode=new Json_Encoder();
                    //call to encode method and assigning response data to variable 'data'
                    //String data=encode.encod_to_json();
                    //response of encoded data
                    //System.out.println(data);


                    //Adding Parameter filepath

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    String filepath = "http://192.168.1.110/echo/uploads" + fileName;

                    dos.writeBytes("Content-Disposition: form-data; name=\"filepath\"" + lineEnd);
                    //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                    //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(filepath); // mobile_no is String variable
                    dos.writeBytes(lineEnd);


                    //Adding Parameter media file(audio,video and image)

                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);
                    dos.writeBytes(lineEnd);
                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();
                    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);


                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn.getResponseMessage();


                    Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

                    if (serverResponseCode == 200) {

                        Log.e("PASSED", "IT WORKS!!! YESS");
                    } else {
                            Log.e("404 ERROR", conn.getResponseMessage());
                    }

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

                } catch (MalformedURLException ex) {
                    ex.printStackTrace();


                    Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                } catch (final Exception e) {
                    e.printStackTrace();

                    Log.e("Upload file Exception",
                            "Exception : " + e.getMessage(), e);
                }
            }
        }
    };
    thread.start();
}

以下是我的node.js服务器:(抱歉,我知道这不是令人印象深刻,我还在学习node.js)

1 var express = require('express')
  2 var app = express()
  3 var multer  = require('multer')
  4 var upload = multer()
  5 
  6 app.get('/', function (req, res) {
  7   res.send('Hello World! (' + Date.now() + ")");
  8 });
  9 
 10 var server = app.listen(3000, function () {
 11   console.log("Express server is started. (port: 3000)");
 12 });
 13 
 14 app.get('/upload', upload.array(), function(req,res){
 15   //console.log(req); //form fields
 16   console.log(res.files); //form files
 17 
 18 
 19   res.send("You got to the upload");
 20 });

我之前没有注释conn.setDoOutput(true),但仍然是同样的错误。我的Node.js服务器现在没有运行,因为我只是在本地测试它,所以如果你尝试ping node.js服务器,它将不会显示当前正在运行。

0 个答案:

没有答案