Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过HttpUrlConnection上载多部分内容_Java_Php_Android_Httpurlconnection_Ioexception - Fatal编程技术网

Java 通过HttpUrlConnection上载多部分内容

Java 通过HttpUrlConnection上载多部分内容,java,php,android,httpurlconnection,ioexception,Java,Php,Android,Httpurlconnection,Ioexception,我想从我的android应用程序上传一个带有几个参数的pdf文件到我的服务器。我花了将近两天的时间来寻找答案,但当我尝试一个解决方案时,总会出现一个新问题。目前,这段代码中没有错误,但仍然没有上载文件,也没有更改数据库。请帮我更正代码。 我现在的代码是这样的: public static void main(String[] args) throws IOException { HttpsFileUploaderConfig config = new HttpsFi

我想从我的android应用程序上传一个带有几个参数的pdf文件到我的服务器。我花了将近两天的时间来寻找答案,但当我尝试一个解决方案时,总会出现一个新问题。目前,这段代码中没有错误,但仍然没有上载文件,也没有更改数据库。请帮我更正代码。 我现在的代码是这样的:

public static void main(String[] args) throws IOException {

    HttpsFileUploaderConfig config = 
         new HttpsFileUploaderConfig(new URL("http://myhost/upload.php"));

    Map<String,String> extraFields = new HashMap<>();
    extraFields.put("u_id", "foo");
    extraFields.put("path", "bar");

    HttpsFileUploaderResult result = HttpsFileUploader.upload(
            config,
            Collections.singletonList(new UploadItemFile(uFile)),  // your file
            extraFields, // your fields
            null);

    if (result.isError()) {
        throw new IOException("Error uploading to " + config.getURL() + ", " + result.getResponseTextNoHtml());
    }
}
1) 上传功能:

public void upload_file(String file_dir, String user_id,String path){

        try {
            String hyphen="--";
        String boundary="Bound";
        String newline="\r\n";

        URL url = new URL("http://117.**.**.**.**:****/upload.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "mutlipart/form-data;boundary="+boundary);

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

        //First Send Parameters so that database can be changed
        oStream.writeBytes(hyphen+boundary+newline);
        oStream.writeBytes("Content-Type: text/plain\n");
        oStream.writeBytes("Content-Disposition: form-data;name=\"u_id\"" + "\r\n");
        oStream.writeBytes(user_id+newline);
        //oStream.flush();

        oStream.writeBytes(hyphen+boundary+newline);
        oStream.writeBytes("Content-Type: text/plain\n");
        oStream.writeBytes("Content-Disposition: form-data;name=\"path\"" + "\r\n");
        oStream.writeBytes(path+newline);
        //oStream.flush();

        oStream.writeBytes(hyphen+boundary+newline);
        oStream.writeBytes("Content-Type: application/pdf\n");
        oStream.writeBytes("Content-Disposition: post-data;name=\"file\";" +
                "filename=\"s1.pdf\"" + "\r\n");

        FileInputStream file = new FileInputStream(file_dir);
        int filesize=file.available();
        Log.d("size", "" + filesize);
        int buffersize = 1024*1024;
        byte buff[] = new byte[buffersize];

        int byteRead = file.read(buff, 0, buffersize);  

        while (byteRead > 0) {

          oStream.write(buff, 0, byteRead);
          byteRead = file.read(buff, 0, buffersize);   
         }

        oStream.writeBytes(newline);

        InputStream iStream = conn.getInputStream();
        char arry[] = new char[1000];
        Reader in = new InputStreamReader(iStream, "UTF-8");
        StringBuilder response = new StringBuilder();
        while(true){
            int rsz = in.read(arry, 0, 1000);
            if (rsz < 0)
                break;
            response.append(arry,0, rsz);
        }
        Log.d("String",response.toString());                                  

         Log.d("Response","Res.."+conn.getResponseCode());

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
public void上传文件(字符串文件目录、字符串用户id、字符串路径){
试一试{
字符串连字符=“--”;
String boundary=“Bound”;
字符串换行符=“\r\n”;
URL=新URL(“http://117.*******:**/upload.php);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
连接设置输出(真);
conn.setDoInput(真);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“内容类型”、“多部分/表单数据;边界=“+boundary”);
DataOutputStream oStream=新的DataOutputStream(conn.getOutputStream());
//首先发送参数,以便更改数据库
oStream.writeBytes(连字符+边界+换行符);
oStream.writeBytes(“内容类型:text/plain\n”);
writeBytes(“内容处置:表单数据;名称=\“u\u id\”+“\r\n”);
oStream.writeBytes(用户标识+换行符);
//oStream.flush();
oStream.writeBytes(连字符+边界+换行符);
oStream.writeBytes(“内容类型:text/plain\n”);
oStream.writeBytes(“内容处置:表单数据;名称=\“路径\+”\r\n”);
oStream.writeBytes(路径+换行符);
//oStream.flush();
oStream.writeBytes(连字符+边界+换行符);
oStream.writeBytes(“内容类型:application/pdf\n”);
writeBytes(“内容处置:post数据;名称=\”文件\“;”+
“文件名=\”s1.pdf\”+“\r\n”);
FileInputStream file=新的FileInputStream(file\u dir);
int filesize=file.available();
Log.d(“大小”,“文件大小”);
int buffersize=1024*1024;
字节buff[]=新字节[buffersize];
int byteRead=file.read(buff,0,buffersize);
while(byteRead>0){
写入(buff,0,byteRead);
byteRead=file.read(buff,0,buffersize);
}
oStream.writeBytes(换行符);
InputStream iStream=conn.getInputStream();
char arry[]=新字符[1000];
Reader in=新的InputStreamReader(iStream,“UTF-8”);
StringBuilder响应=新建StringBuilder();
while(true){
int rsz=in.read(arry,0,1000);
如果(rsz<0)
打破
追加(arry,0,rsz);
}
Log.d(“字符串”,response.toString());
Log.d(“Response”、“Res..”+conn.getResponseCode());
}捕获(格式错误){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
2) 我的服务器上的php文件:upload.php

<?php

    require_once 'db_connect.php';

    $obj = new DB_Connect();
    $conn = $obj->connect();

    if(!$conn){
        echo mysql_error();
    }

    var_dump($_POST);
    var_dump($_REQUEST);
    print_r($_FILES);

    $file_path = "Docs/";
    $u_id=$_POST["u_id"];
    $path=$_POST["path"];
    $file = $path."/".basename( $_FILES['file']['name']);

    $qrry = mysql_query("insert into file values('$file','$u_id',now(),'pdf')");
    if(!$qrry)
    echo "error";

    $file_path = $file_path . basename( $_FILES['file']['name']);
    if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

程序生成的多部分消息是错误的:缺少主体,缺少边界声明。。。这是您应该生成的格式:

Message-ID: <000000001>
MIME-Version: 1.0
Content-Type: multipart/mixed; 
    boundary="----=_Part_0_842618406.1437326651362"

------=_Part_0_842618406.1437326651362
Content-Type: application/octet-stream; name=myfile.pdf
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=myfile.pdf

<...binary data...>
------=_Part_0_842618406.1437326651362--
消息ID:
MIME版本:1.0
内容类型:多部分/混合;
boundary=“---=\u Part\u 0\u 842618406.1437326651362”
------=_部分_0_842618406.1437326651362
内容类型:应用程序/八位字节流;name=myfile.pdf
内容传输编码:7bit
内容处置:附件;filename=myfile.pdf
------=_部分_0_842618406.1437326651362--
我真诚地建议您不要从头开始制作MIME消息;相反,通过使用Java Mail API,您可以省去麻烦,例如,使用以下程序:

public void createMultipartMessage(File[] files, OutputStream out)
    throws MessagingException,
    IOException
{
    Session session=Session.getDefaultInstance(System.getProperties());
    MimeMessage mime=new MimeMessage(session);
    Multipart multipart=new MimeMultipart();
    BodyPart part;

    // Send form data (as for http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2):
    part=new MimeBodyPart();
    part.setDisposition("Content-Disposition: form-data; name=\"<name>\"");
    part.setContent("<value>");        
    multipart.addBodyPart(part);

    // Send binary files:
    for (File file : files)
    {
        part=new MimeBodyPart();
        part.setFileName(file.getName());
        DataHandler dh=new DataHandler(new FileDataSource(file));
        part.setDataHandler(dh);
        multipart.addBodyPart(part);
    }
    mime.setContent(multipart);
    mime.writeTo(out);
}
public void createMultipartMessage(文件[]文件,输出流输出)
抛出MessagingException,
IOException
{
Session Session=Session.getDefaultInstance(System.getProperties());
MimeMessage mime=新MimeMessage(会话);
Multipart Multipart=新的MimeMultipart();
身体部分;
//发送表单数据(如http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2):
零件=新的MimeBodyPart();
setDisposition(“内容处置:表单数据;名称=\”\”);
第.部分内容(“”);
多部件。添加车身部件(部件);
//发送二进制文件:
用于(文件:文件)
{
零件=新的MimeBodyPart();
part.setFileName(file.getName());
DataHandler dh=新的DataHandler(新文件数据源(文件));
部分.setDataHandler(dh);
多部件。添加车身部件(部件);
}
mime.setContent(多部分);
默剧。写(出);
}
您必须在运行时中包含mail-1.4.1.jar和activation-1.1.1.jar库。

您可以使用最小值。尽管名称不同,它也适用于HTTP。它只有大约20K,实际上只是
HttpURLConnection
的包装器,所以我觉得它非常适合Android。它使您不必了解多部分上传、编码等内容。也可从以下网址获得

您的示例如下所示:

public static void main(String[] args) throws IOException {

    HttpsFileUploaderConfig config = 
         new HttpsFileUploaderConfig(new URL("http://myhost/upload.php"));

    Map<String,String> extraFields = new HashMap<>();
    extraFields.put("u_id", "foo");
    extraFields.put("path", "bar");

    HttpsFileUploaderResult result = HttpsFileUploader.upload(
            config,
            Collections.singletonList(new UploadItemFile(uFile)),  // your file
            extraFields, // your fields
            null);

    if (result.isError()) {
        throw new IOException("Error uploading to " + config.getURL() + ", " + result.getResponseTextNoHtml());
    }
}
publicstaticvoidmain(字符串[]args)引发IOException{
HttpsFileUploaderConfig配置=
新建HttpsFileUploaderConfig(新URL(“http://myhost/upload.php"));
Map extraFields=new HashMap();
外部字段。put(“u_id”、“foo”);
外部字段。放置(“路径”、“栏”);
HttpsFileUploaderResult结果=HttpsFileUploader.upload(
配置,
Collections.singletonList(新的UploadItemFile(uFile)),//您的文件
extraFields,//您的字段
无效);
if(result.isError()){
抛出新的IOException(“上传到“+config.getURL()+”、“+result.getResponseTextNoHtml()时出错”);
}
}

评论不用于扩展讨论;