SparkJava:上传文件在Spark java框架中不起作用 [英] SparkJava: Upload file did't work in Spark java framework

查看:151
本文介绍了SparkJava:上传文件在Spark java框架中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从stackoverflow中获得了一些关于在spark java中上传文件的方法,但是我尝试了并且没有工作。

I have got some method from the stackoverflow about uploading file in spark java, but I try and did't work.

post("/upload",
          (request, response) -> {

            if (request.raw().getAttribute("org.eclipse.jetty.multipartConfig") == null) {
                MultipartConfigElement multipartConfigElement = new MultipartConfigElement(System.getProperty("java.io.tmpdir"));
                request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
            }
            Part file = request.raw().getPart("file");
            Part name = request.raw().getPart("name");
            String filename = file.getName();
            if(name.getSize() > 0){
                try{
                    filename = IOUtils.toString(name.getInputStream(), StandardCharsets.UTF_8);
                } catch(Exception e){
                    e.printStackTrace();
                }
            }
            Path filePath = Paths.get(".",filename);
            Files.copy(file.getInputStream(),filePath);
            return "Done!";
          });

}

我使用邮递员发送邮件

我得到了这样的错误

错误指向代码零件文件= request.raw()。getPart(file);

推荐答案

post("/upload", "multipart/form-data", (request, response) -> {

String location = "image";          // the directory location where files will be stored
long maxFileSize = 100000000;       // the maximum size allowed for uploaded files
long maxRequestSize = 100000000;    // the maximum size allowed for multipart/form-data requests
int fileSizeThreshold = 1024;       // the size threshold after which files will be written to disk

MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
     location, maxFileSize, maxRequestSize, fileSizeThreshold);
 request.raw().setAttribute("org.eclipse.jetty.multipartConfig",
     multipartConfigElement);

Collection<Part> parts = request.raw().getParts();
for (Part part : parts) {
   System.out.println("Name: " + part.getName());
   System.out.println("Size: " + part.getSize());
   System.out.println("Filename: " + part.getSubmittedFileName());
}

String fName = request.raw().getPart("file").getSubmittedFileName();
System.out.println("Title: " + request.raw().getParameter("title"));
System.out.println("File: " + fName);

Part uploadedFile = request.raw().getPart("file");
Path out = Paths.get("image/" + fName);
try (final InputStream in = uploadedFile.getInputStream()) {
   Files.copy(in, out);
   uploadedFile.delete();
}
// cleanup
multipartConfigElement = null;
parts = null;
uploadedFile = null;

return "OK";
});

这很有效,我在 https://groups.google.com/forum/#!msg/sparkjava/fjO64BP1UQw/CsxdNVz7qrAJ

这篇关于SparkJava:上传文件在Spark java框架中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆