• Winform(C#)——向服务器上传文件代码


    public string  UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
            {
                string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\") + 1);
                uriString = "http://192.168.0.62/pdf/";
                string NewFileName = fileName;
                if (IsAutoRename)
                {
                    NewFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
                }

                string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
                if (uriString.EndsWith("/") == false) uriString = uriString + "/";

                uriString = uriString + NewFileName;

                ///  创建WebClient实例 
                WebClient myWebClient = new WebClient();
                myWebClient.Credentials = CredentialCache.DefaultCredentials;

                try
                {
                    // 要上传的文件 
                    FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                    BinaryReader r = new BinaryReader(fs);
                    byte[] postArray = r.ReadBytes((int)fs.Length);
                    Stream postStream = myWebClient.OpenWrite(uriString, "PUT");

                    try
                    {
                        // 使用UploadFile方法可以用下面的格式
                        
    // myWebClient.UploadFile(uriString,"PUT",fileNamePath); 

                        if (postStream.CanWrite)
                        {
                            postStream.Write(postArray, 0, postArray.Length);
                            postStream.Close();
                            fs.Dispose();
                        }
                        else
                        {
                            postStream.Close();
                            fs.Dispose();
                        }
                    }
                    catch (Exception err)
                    {
                        postStream.Close();
                        fs.Dispose();
                    }
                    finally
                    {
                        postStream.Close();
                        fs.Dispose();
                    }
                    return NewFileName;
                }
                catch
                {
                    ///
                }
                return NewFileName;
            }
  • 相关阅读:
    Mongodb---记一次事故故障
    扎克伯格的中文夜:想要成功就不能放弃
    TTS-零基础入门之停止列表中单条语音播报
    卡尔曼滤波(Kalman Filter) 的进一步讨论
    2014.8.12-AKKA和Actor model 分布式开发环境学习小结
    c# 删除程序占用的文件,强力删除文件,彻底删除文件,解除文件占用
    Spring源代码解析和配置文件载入
    java调用c++ dll出现中文乱码
    Android任务栈TaskStack
    应用中清理缓存应用实现
  • 原文地址:https://www.cnblogs.com/bluewhy/p/5242316.html
Copyright © 2020-2023  润新知