django实现文件上传到服务器

django实现文件上传到服务器,第1张

response = requests.post(PATH, data={'document_name': document_path, 'file': base64.b64encode(file.read())}) 这个方法其实就是将文件信息和转成base64的文件发到服务器那边,那边就是以下的方法存入服务器

文件存入本地的方法

小于2.5M时,会放在 InMemoryFileUploadFile(内存里面) 对象里面;

大于2.5M时,会放在 TemporaryFileUploadFile (磁盘文件)里面

而 celery 做pickle_dump时会去找file object的encoding

这个encoding目前发现只能存在 InMemoryFileUploadFile 对象里面

所以,我们只有将所有上传文件都放到 InMemoryFileUploadFile 里面,才能通过celery

可以通过在settings里面设置

来修改策略使所有50M以内的文件都存在 InMemoryFileUploadFile 里面

这个设置谨慎使用,防止内存溢出!!!

使用的是WebClient而不是ftp

首先,我们先来定义一个类UpLoadFile,这个类就是文件上传类。代码如下:

public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)

{

int indexOf = 0

if (fileNamePath.Contains(@"\"))

{

indexOf = fileNamePath.LastIndexOf(@"\")

}

else if (fileNamePath.Contains("/"))

{

indexOf = fileNamePath.LastIndexOf("/")

}

string fileName = fileNamePath.Substring(indexOf + 1)

string NewFileName = fileName

if (IsAutoRename)

{

NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + 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

// 要上传的文件

FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read)

//FileStream fs = OpenFile()

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()

throw err

}

finally

{

postStream.Close()

fs.Dispose()

}

}

好了,定义好这个类之后就看我们怎么调用它了。在这里我给出一个例子:

单击某个按钮事件:

private void center_Click(object sender, EventArgs e)

{

//上传文件

//得到文件名,文件扩展名,服务器路径

string filePath = filename.Text//需要上传的文件,在这里可以根据需要采用OpenFileDialog来获取文件

string server = @"http://www.thylx.com/” //上传路径

//创建webclient实例

WebClient myWebClient = new WebClient()

try

{

//使用Uploadfile方法上传

UpLoadFile(filePath, server, true)

MessageBox.Show("上传成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information)

}

catch (Exception ex)

{

MessageBox.Show(ex.Message)

return

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/6064850.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-13
下一篇2023-03-13

发表评论

登录后才能评论

评论列表(0条)

    保存