Модераторы: Alexeis
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Отправка Файла на сервер, upload file 
:(
    Опции темы
ishimcity
Дата 21.1.2009, 10:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 230
Регистрация: 1.6.2007
Где: Тюменская область . Ишим

Репутация: 1
Всего: 1



Здраствуйте ребята! Реализую код для отправки файла на сервер. все нормально компилируется для КПК но при запуске на девайся выкидвает ошибку ProtocolViolationException с чем это связано?спасибо

Код

public static string uploadfileex( string uploadfile, string url, 
    string fileformname, string contenttype,namevaluecollection querystring )
{
    if( (fileformname== null) ||
        (fileformname.length ==0))
    {
        fileformname = "file";
    }

    if( (contenttype== null) ||
        (contenttype.length ==0))
    {
        contenttype = "application/octet-stream";
    }


    string postdata;
    postdata = "?";
    if (querystring!=null)
    {
        foreach(string key in querystring.keys)
        {
            postdata+= key +"=" + querystring.get(key)+"&";
        }
    }
    uri uri = new uri(url+postdata);


    string boundary = "----------" + datetime.now.ticks.tostring("x");
    httpwebrequest webrequest = (httpwebrequest)webrequest.create(uri);
    webrequest.cookiecontainer = cookies;
    webrequest.contenttype = "multipart/form-data; boundary=" + boundary;
    webrequest.method = "post";


    // build up the post message header

    stringbuilder sb = new stringbuilder();
    sb.append("--");
    sb.append(boundary);
    sb.append("\r\n");
    sb.append("content-disposition: form-data; name=\"");
    sb.append(fileformname);
    sb.append("\"; filename=\"");
    sb.append(path.getfilename(uploadfile));
    sb.append("\"");
    sb.append("\r\n");
    sb.append("content-type: ");
    sb.append(contenttype);
    sb.append("\r\n");
    sb.append("\r\n");            

    string postheader = sb.tostring();
    byte[] postheaderbytes = encoding.utf8.getbytes(postheader);

    // build the trailing boundary string as a byte array

    // ensuring the boundary appears on a line by itself

    byte[] boundarybytes = 
           encoding.ascii.getbytes("\r\n--" + boundary + "\r\n");

    filestream filestream = new filestream(uploadfile, 
                                filemode.open, fileaccess.read);
    long length = postheaderbytes.length + filestream.length + 
                                           boundarybytes.length;
    webrequest.contentlength = length;

    stream requeststream = webrequest.getrequeststream();

    // write out our post header

    requeststream.write(postheaderbytes, 0, postheaderbytes.length);

    // write out the file contents

    byte[] buffer = new byte[checked((uint)math.min(4096, 
                             (int)filestream.length))];
    int bytesread = 0;
    while ( (bytesread = filestream.read(buffer, 0, buffer.length)) != 0 )
        requeststream.write(buffer, 0, bytesread);

    // write out the trailing boundary

    requeststream.write(boundarybytes, 0, boundarybytes.length);
    webresponse responce = webrequest.getresponse();
    stream s = responce.getresponsestream();
    streamreader sr = new streamreader(s);

    return sr.readtoend();
}



Код

uploadfile = "c:\\test.doc";
string outdata = UploadFileEx(uploadfile,"http://localhost/test.php","file", "application/octet-stream", 
     querystring);



В чем косяк? голову сломал уже
PM MAIL ICQ Skype YIM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Программирование мобильных устройств"
Alexeis

Раздел посвящен программированию мобильных устройств.

Все остальные вопросы по мобильным устройствам (КПК, смартфоны, телефоны, фотоаппараты и т.п),
не имеющие отношения к программированию, просьба размещать в разделе КПК, смартфоны, мобильники

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Платформы Windows Mobile и Windows Embedded | Следующая тема »


 




[ Время генерации скрипта: 0.0430 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.