【问题标题】:Unable to fetch Input File in servlet from request object无法从请求对象获取 servlet 中的输入文件
【发布时间】:2018-04-02 14:04:21
【问题描述】:

我需要从表单中获取上传的输入文件并将其保存到 mysql 数据库中。这里我无法从请求对象中获取输入文件。

我的 servlet:

@Component(service = Servlet.class, property = {

"service.description=" + "************** Servlet",

"sling.servlet.methods=" + HttpConstants.METHOD_POST,

"sling.servlet.paths=" + "/bin/uploadtestservlet" })

public class UploadTestServlet extends SlingAllMethodsServlet{


@Reference

UploadAdmissionFormService uploadService; 

private static final long serialVersionUID = 1L;

private final Logger LOGGER = LoggerFactory

.getLogger(UploadTestServlet .class); 

protected void doPost(SlingHttpServletRequest request,

SlingHttpServletResponse response) {



try{

if(ServletFileUpload.isMultipartContent(request)){

List<File> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

for(File item : multiparts){

LOGGER.info("Name :::"+new File(item.getName()).getName()); //

}

}catch(Exception e){

}

}

我的 js:

$("#uploadSubmit").click(function(e) {

$.ajax({

type: "POST",

            url: "/bin/uploadAdmissionForm",

            data: 'passport=' +$('#uploadPhoto').get(0).files.item(0),

            success: function(msg) {          

        },
        });
    });

HTML:

<form method="POST" enctype="multipart/form-data" id="upload-details-form">

<input type="file" name="uploadPhoto" id="uploadPhoto" class="uploadPhoto">

<div class="upload-photo">

<div class="upload-photo-content">

<h4>UPLOAD PHOTO</h4>

<p>Upload your recent passport size (3.5 x 4.5cm) color photograph (format should be jpg, gif, png, jpeg, bmp and maximum file size alloted is 1 MB)</p>

</div></div><form>

例外

Exception occurred in doPost :the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8

即使我在表单级别添加了enctype="multipart/form-data",这个错误还是会被抛出。有人可以在这里帮助我吗?谢谢

【问题讨论】:

    标签: javascript ajax servlets aem sling


    【解决方案1】:

    您的 ajax 没有指定文件。您必须将 processData:false,contentType:false 添加到您的方法中。

    $("#uploadSubmit").click(function(e) {
     $.ajax({
      type: "POST",
      url: "/bin/uploadAdmissionForm",
      data: new FormData( this ), //this is needed
      processData: false, //this is needed
      success: function(data) {  
        //handle return here
            },
    contentType: false //this is needed
          });
        });
    

    这里有一些关于它的链接:

    jQuery AJAX file upload PHP

    upload file through ajax

    How to upload a file using jQuery.ajax and FormData

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 2012-03-26
      • 2016-03-15
      • 2019-03-12
      • 2019-04-28
      • 2020-04-26
      • 1970-01-01
      • 2019-04-21
      • 2021-12-31
      相关资源
      最近更新 更多