spring ajax文件上传问题

发布于 2024-10-26 02:27:27 字数 2131 浏览 1 评论 0原文

我有一个简单的表单,其中包含上传图像的选项,但要上传文件,我没有使用此方法

<form:input path="logoData" id="image" type="file" />

,而是使用 ajax上传jquery pulgin。 问题是 upload.parseRequest(request) 在以下代码中返回 null :

@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest request) throws FileUploadException{

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List<FileItem> items = upload.parseRequest(request);
     System.out.println("====ITEMS====" + items.size());


     System.out.println("----REQUEST---" +request.getParameter("uploadImg"));
        System.out.println("-----SIZE----" +request.getParameterMap().size());
        Map<String, String> map = request.getParameterMap();

        for(Map.Entry<String, String> entry : map.entrySet()){
            System.out.println("----KEY---" + entry.getKey() + "----value---" + entry.getValue());
        }


 // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    System.out.println("----IS MULTIPART---" +isMultipart);
    return "hello";
}

日志输出为:

====ITEMS====0
----请求---空
-----尺寸----0
----IS MULTIPART---true

我的 javascript 代码是:

new AjaxUpload('#upload', {
action : my_url+ 'methodName/upload.htm',
name : 'uploadImg',
autoSubmit : true,
responseType: 'html',
onChange: function(file, extension){   },   
onSubmit: function(file, extension) {

},
onComplete: function(file, html) {
    alert(file);
    alert(html);

}

});

IS MULTIPART 显示 true,但是如何获取文件名以及如何存储它。我尝试过一个没有 ajax 的示例,并且使用数据类型 CommonsMultipartFile 可以正常工作。 另外,我在 PHP 中使用了 ajaxupload ,我得到的文件名是 $_FILES['image']['name'] 但在 java 中不知道,因为我是 java 新手。 我在这个网站上遵循了类似的问题,但没有成功。

谢谢。

I have a simple form with an option to upload image but to upload a file I am not using this method

<form:input path="logoData" id="image" type="file" />

instead I am using ajax upload jquery pulgin.
The problem is upload.parseRequest(request) is returning null in the below code :

@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest request) throws FileUploadException{

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List<FileItem> items = upload.parseRequest(request);
     System.out.println("====ITEMS====" + items.size());


     System.out.println("----REQUEST---" +request.getParameter("uploadImg"));
        System.out.println("-----SIZE----" +request.getParameterMap().size());
        Map<String, String> map = request.getParameterMap();

        for(Map.Entry<String, String> entry : map.entrySet()){
            System.out.println("----KEY---" + entry.getKey() + "----value---" + entry.getValue());
        }


 // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    System.out.println("----IS MULTIPART---" +isMultipart);
    return "hello";
}

Output of log is :

====ITEMS====0
----REQUEST---null
-----SIZE----0
----IS MULTIPART---true

And my javascript code is :

new AjaxUpload('#upload', {
action : my_url+ 'methodName/upload.htm',
name : 'uploadImg',
autoSubmit : true,
responseType: 'html',
onChange: function(file, extension){   },   
onSubmit: function(file, extension) {

},
onComplete: function(file, html) {
    alert(file);
    alert(html);

}

});

IS MULTIPART is showing true but how to get the file name and how to store it. I have tried an example without ajax and it works fine using datatype CommonsMultipartFile.
Also I have used ajaxupload in PHP and I get the filename as $_FILES['image']['name'] but no idea in java as I am new to java.
I have followed my similar question on this site but no success.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隐诗 2024-11-02 02:27:27

您可以将其缩短。您需要一个多部分解析器:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

然后:

@Controller
public class FileUpoadController {

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            // store the bytes somewhere
           return "redirect:uploadSuccess";
       } else {
           return "redirect:uploadFailure";
       }
    }

}

You can make this shorter. You need a multipart-resolver:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

And then:

@Controller
public class FileUpoadController {

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            // store the bytes somewhere
           return "redirect:uploadSuccess";
       } else {
           return "redirect:uploadFailure";
       }
    }

}
山川志 2024-11-02 02:27:27
@RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {

            System.out.println("File name:"+ file.getOriginalFilename());
            //byte[] bytes = file.getBytes();
            System.out.println("Content type:"+ file.getContentType());
            String [] contentType = file.getContentType().split("/");
            String fileType = contentType[contentType.length-1];
            System.out.println("File type:"+ fileType);
            System.out.println("File size:"+ (file.getSize()/1024) + "KB");

            String path = context.getRealPath( "/resources/images/");
            System.out.println("Path: " + path);



            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                outputStream = new FileOutputStream(path + file.getOriginalFilename());
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            int readBytes = 0;
            byte[] buffer = new byte[8192];
            try {
                while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                            outputStream.write(buffer, 0, readBytes);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            // store the bytes somewhere
            return "theme";
    }
    else
        return "uploadError";

}
@RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {

            System.out.println("File name:"+ file.getOriginalFilename());
            //byte[] bytes = file.getBytes();
            System.out.println("Content type:"+ file.getContentType());
            String [] contentType = file.getContentType().split("/");
            String fileType = contentType[contentType.length-1];
            System.out.println("File type:"+ fileType);
            System.out.println("File size:"+ (file.getSize()/1024) + "KB");

            String path = context.getRealPath( "/resources/images/");
            System.out.println("Path: " + path);



            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                outputStream = new FileOutputStream(path + file.getOriginalFilename());
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            int readBytes = 0;
            byte[] buffer = new byte[8192];
            try {
                while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                            outputStream.write(buffer, 0, readBytes);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            // store the bytes somewhere
            return "theme";
    }
    else
        return "uploadError";

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文