文件上传正在使用 Postman,但不适用于从浏览器运行的 Javascript

Posted

技术标签:

【中文标题】文件上传正在使用 Postman,但不适用于从浏览器运行的 Javascript【英文标题】:File Upload is working with Postman but not with Javascript running from browser 【发布时间】:2020-11-19 23:14:24 【问题描述】:

我正在通过 AJAX、Javscript 和 Spring MVC 控制器进行文件上传,并且在这个过程控制器中能够读取从 Postman 传递的文件,但不能从浏览器中运行的 javascript 和 AJAX 读取。

邮递员详细信息在下面的屏幕截图中。

Postman 请求的控制器日志如下所述。

2020-07-30 10:24:01,670 [http-nio-8080-exec-541] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'Search' processing POST request for [/bulkuploadreportstg]
2020-07-30 10:24:01,695 [http-nio-8080-exec-541] DEBUG o.s.w.m.c.CommonsMultipartResolver - Found multipart file [blreportexcel] of size 11856 bytes with original filename [BerichtInfo_Datei_Export_201973112055.xlsx], stored at [D:\DTS\Apache_8.5.43\work\Catalina\localhost\upload_113af7dc_1739a8f843a__7fe8_00000001.tmp]
2020-07-30 10:24:01,695 [http-nio-8080-exec-541] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /bulkuploadreportstg
2020-07-30 10:24:01,695 [http-nio-8080-exec-541] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'BulkUploadController'
2020-07-30 10:24:01,757 [http-nio-8080-exec-541] INFO   Received file to upload the data into staging table is:org.springframework.web.multipart.commons.CommonsMultipartFile@b67a7f0
2020-07-30 10:24:01,757 [http-nio-8080-exec-541] INFO   I am inside bulk upload stage controller
2020-07-30 10:24:01,757 [http-nio-8080-exec-541] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'Search': assuming HandlerAdapter completed request handling
2020-07-30 10:24:01,757 [http-nio-8080-exec-541] DEBUG o.s.w.m.c.CommonsMultipartResolver - Cleaning up multipart file [blreportexcel] with original filename [BerichtInfo_Datei_Export_201973112055.xlsx], stored at [D:\DTS\Apache_8.5.43\work\Catalina\localhost\upload_113af7dc_1739a8f843a__7fe8_00000001.tmp]
2020-07-30 10:24:01,757 [http-nio-8080-exec-541] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request

下面是 html 组件以及各自的 JQUERY 和 AJAX。

<div class="container-fluid">
    <div class="card">
                    <div class="card-header bg-info">
                        BERICHT DATEI IMPORTIEREN
                    </div>
                    <div class="card-body">
                            <form id="blkuploadform2" enctype="multipart/form-data">
                                <div class="form-group">
                                            <h6>Datei Importieren Method :</h6>
                                            <p>Diese Seite wird verwendet, um die Datei mit 1 oder mehr als 1 Berichtsdatensätzen gleichzeitig in die Datenbank hochzuladen.</p>
                                            <br>
                                            <input type="file" id="blkUploadReport2" name="blkUploadReport2">  <span class="fas fa-asterisk"></span>
                                </div>
                            </form>
                            <div class="col-sm-offset-2 col-sm-6">
                                    <button class="btn btn-success btn-raised btn-sm" id="saveEdit2" onClick="bulkupdValidator2()">
                                        IMPORTIEREN <span class="fas fa-save"></span> 
                                    </button>                   
                            </div>
                    </div>
        </div>
</div>
<div class="modal fade" id="confirm-save" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">            
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel1">Bestätigung</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>            
                <div class="modal-body">
                   <p>Sie sind im Begriff Berichtsdaten zu speichern. Möchten Sie fortfahren?</p>                    
                </div>                
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">NEIN</button>
                    <button type="button" class="btn btn-success" data-dismiss="modal" onClick="blksavedata('report')">JA</button>
                </div>
            </div>
        </div>
</div>
<div class="modal fade" id="error-message" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">            
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel2">Fehler</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>            
                <div class="modal-body">
                   <p id="error"></p>                    
                </div>                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
                </div>
            </div>
        </div>
</div>
<div class="modal fade" id="success-message" tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">            
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel3">Erfolg</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>            
                <div class="modal-body">
                   <p id="success"></p>                   
                </div>                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
                </div>
            </div>
        </div>
</div>
//Function to validate the File input using method 2.
function bulkupdValidator2()
    if($('#blkuploadform2').valid())
        $('#confirm-save').modal('show');
        console.log("I am success");
    
    else
        document.getElementById("error").innerText="Bitte füllen Sie die erforderlichen Felder mit rotem Text aus.";
         $('#error-message').modal('show');
    
    


$(document).ready(function()
    $('#blkuploadform2').validate(
        rules:
            blkUploadReport2:
                required:true,
                extension:'xlsx'
            
        ,
        messages:
            blkUploadReport2:
                required:"Bitte laden Sie die Datei im gewünschten Format (.xlsx) hoch.",
                extension:"Bitte laden Sie die Datei im gewünschten Format (.xlsx) hoch."
            
        
    )
)

//Function to Validate the data from uploaded file and load them into staging tables accordingly.

function blksavedata(typeOfData)

    $('#confirm-save').modal('hide');
    var fileInput=document.getElementById("blkuploadform2");
    var form=new FormData();
    console.log(fileInput[0].files[0]);
    console.log(fileInput[0].files[0].name);
    form.append('file',fileInput[0].files[0],fileInput[0].files[0].name);
    var fileType=typeOfData;
    
    if (fileType=='report')
        
         $.ajax(
             type:"POST",
             url:"/DTSDBL/bulkuploadreportstg",
             data:form,
             processData: false,
             contentType: false,
             success:function(data)                
                console.log("I am success returned form controller");                                                
             ,
             error:function(e)
                console.log("I am error returned form controller");              
             
            );
        
        
     

来自 Javascript 和 Ajax 的请求的控制器日志:

2020-07-30 10:23:18,388 [http-nio-8080-exec-535] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'Search' processing POST request for [/bulkuploadreportstg]
2020-07-30 10:23:18,435 [http-nio-8080-exec-535] DEBUG o.s.w.m.c.CommonsMultipartResolver - Found multipart file [file] of size 11856 bytes with original filename [BerichtInfo_Datei_Export_201973112055.xlsx], stored at [D:\DTS\Apache_8.5.43\work\Catalina\localhost\\upload_113af7dc_1739a8f843a__7fe8_00000000.tmp]
2020-07-30 10:23:18,435 [http-nio-8080-exec-535] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /bulkuploadreportstg
2020-07-30 10:23:18,435 [http-nio-8080-exec-535] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'BulkUploadController'
2020-07-30 10:23:18,450 [http-nio-8080-exec-535] DEBUG o.s.web.cors.DefaultCorsProcessor - Skip CORS processing: request is from same origin
2020-07-30 10:23:18,450 [http-nio-8080-exec-535] INFO  DTSDB - Received file to upload the data into staging table is:null
2020-07-30 10:23:18,450 [http-nio-8080-exec-535] INFO  DTSDB - I am inside bulk upload stage controller
2020-07-30 10:23:18,481 [http-nio-8080-exec-535] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'Search': assuming HandlerAdapter completed request handling
2020-07-30 10:23:18,481 [http-nio-8080-exec-535] DEBUG o.s.w.m.c.CommonsMultipartResolver - Cleaning up multipart file [file] with original filename [BerichtInfo_Datei_Export_201973112055.xlsx], stored at [D:\DTS\Apache_8.5.43\work\Catalina\localhost\\upload_113af7dc_1739a8f843a__7fe8_00000000.tmp]
2020-07-30 10:23:18,481 [http-nio-8080-exec-535] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request

请帮我看看我在 Javascript 和 Ajax 请求中遗漏了什么?

【问题讨论】:

浏览器控制台有错误吗? 我没有在浏览器中看到任何错误。如果我查看 Controller log ,我看到文件已找到,但是当我尝试打印时,它显示为 null 而不是 org.springframework.web.multipart.commons.CommonsMultipartFile@b67a7f0 ,如 Postman 请求中所示。 我认为 getElementById 不返回数组。为什么这不会导致控制台错误? 文件正在发送到 Controller 。根据日志,我看到它正在被发现。问题是为什么当从浏览器发送而不是从 Postman 发送时无法读取它 【参考方案1】:

我已修复它,因为我在通过 AJAX 发送它时使用了错误的文件名,因为它与 Controller 中的 Multipart 文件名不匹配。由于这个原因,文件未被识别。现在文件名已更改为与控制器请求正文中的多部分文件名相同,并且可以正常工作。一个简单的错误会花费 1 天时间。

【讨论】:

以上是关于文件上传正在使用 Postman,但不适用于从浏览器运行的 Javascript的主要内容,如果未能解决你的问题,请参考以下文章

Multipart POST 适用于 Postman,但不适用于 Angular Http Client

Apple App Site Association 在 Postman 中工作,但不适用于在线验证器

验证不适用于引导文件上传

使用 JWT 访问 Rest API 适用于 Postman 但不适用于 Axios

PHP/jQuery S3 上传不适用于带空格的文件

iOS 上的 Plupload 仅适用于新照片,不适用于相机胶卷