【问题标题】:Getting MIME type 'application/octet-stream' after Uploading a csv file?上传 csv 文件后获取 MIME 类型“application/octet-stream”?
【发布时间】:2021-11-15 00:49:03
【问题描述】:

当我尝试上传csv 文件时,其MIME 类型更改为application/octet-stream。虽然我在表单中指定了enctype="multipart/form-data",但我该如何解决?

<div class="container mt-5">
        <form action="{{route('fileUpload')}}" method="POST" enctype="multipart/form-data">
            <h3 class="text-center mb-5">Download file</h3>
            @csrf
            @if ($message = Session::get('success'))
                <div class="alert alert-success">
                    <strong>{{ $message }}</strong>
                </div>
            @endif

            @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <div class="custom-file">
                <input type="file" name="file" class="custom-file-input" id="chooseFile">
                <label class="custom-file-label" for="chooseFile">Choose file</label>
            </div>

            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload
            </button>
        </form>
</div>

【问题讨论】:

标签: php laravel


【解决方案1】:

最近我遇到了同样的问题 - 我正在尝试使用此代码(在客户端)将 *.docx 文件上传到服务器:


function uploadFile(file) {

    const formData = new FormData();
    formData.append('file', file);

    const config = {
        headers: {
            'Content-Type': 'multipart/form-data',
            'Accept': 'application/json',
        }
    }

    return axios.post('/file/upload', formData, config);
}

服务器部分:


// part from FileController.php 
private const ALLOWED_TYPES = [
        'image/png',
        'image/jpeg',
        'image/gif',
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    ];



// FileUploader.php
class FileUploader {

public static function uploadFile($file, $maxSize, $uploadPath, array $allowedTypes = []): string
    {
        if( !in_array($file->getMimeType(), $allowedTypes) ) {
            throw new \Exception("File type ({$file->getMimeType()}) not allowed." );
        }

        if( $file->getSize() > $maxSize ) {
            throw new \Exception('File too big.');
        }

        $name = $file->getClientOriginalName();
        $file->move( storage_path($uploadPath), $name );

        return $name;
    }
}

对于大多数 *.docx 文件上传是成功的 - 它可以正常工作,但对于某些 sample.docx 文件 - 文件类型(应用程序/八位字节流)不允许。强>返回。这很奇怪——只有这个文件不能上传。

之前的 cmets 中提供的链接说明当服务器无法确定文件 mime-type 时会发生这种情况。所以我通过创建一个包含先前文件内容的新文件来修复它 - 现在它可以工作了。

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2012-01-18
    • 2017-05-21
    相关资源
    最近更新 更多