如何获取文件的content_type

时间:2017-11-07 12:00:09

标签: python django

我正在创建一个文件。我发送base64字符串作为参数。这是我的代码:

def save_file(request_data):
    """
    """
    data = base64.b64decode(request_data.get('file'))
    file_type = imghdr.what('', h=data)
    if file_type not in ['pdf', 'txt', 'xls', 'xlsx', 'html']:
        return ({"msg": "Upload a valid file. The file you uploaded is not acceptable"}, 400)
    file = tempfile.TemporaryFile()
    file.write(data)
    file_size = os.fstat(file.fileno()).st_size
    name = str(file.name)+"."+str(file_type)
    content_type = magic.from_file(name, mime=True)
    uploaded_file = InMemoryUploadedFile(file=file, field_name='path', name=name,
                                        content_type=content_type, size=file_size, charset='utf-8')
    UploadedFile.objects.create(path=uploaded_file,
                         name=request_data.get('name'),
                         meta_info=request_data.get('meta_info', '{}'),
                         status=request_data.get('status', 'I'))
    file.close()
    return ({"msg": "File created successfully"}, 200)

我收到此错误:

  

文件不存在:32.jpeg

在这一行:

  

content_type = magic.from_file(name,mime = True)

有谁知道如何从base64字符串中获取内容类型?

1 个答案:

答案 0 :(得分:0)

here

窃取
Sub ExportToWord()

Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim SrcePath As String

    Range("G3:J29").Copy

    'Create an Instance of MS Word
  On Error Resume Next

    'Is MS Word already opened?
      Set WordApp = GetObject(class:="Word.Application")

    'Clear the error between errors
      Err.Clear

    'If MS Word is not already open then open MS Word
      If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

    'Handle if the Word Application is not found
      If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
      End If

  On Error GoTo 0

    'Make MS Word Visible and Active
    WordApp.Visible = True
    WordApp.Activate

    'Create a New Document
    Set myDoc = WordApp.Documents.Add

    'Paste Table into MS Word
    myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

    'Autofit Table so it fits inside Word Document
    Set WordTable = myDoc.Tables(1)
    WordTable.AutoFitBehavior (wdAutoFitWindow)

    'Insert Header logo
    SrcePath = "C:\Users\SIDVI\Pictures\logo.gif"

    myDoc.Sections.Item(1).Headers(wdHeaderFooterPrimary) _
        .Range.InlineShapes.AddPicture (SrcePath)

    'Prompts users to save document
    Documents.Save NoPrompt:=False

    If Err.Number = 462 Then
        GoTo EndRoutine
    End If

EndRoutine:
'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

End Sub