首页 \ 问答 \ Spring-boot Thymeleaf Multipart文件上传(Spring-boot Thymeleaf Multipart file upload)

Spring-boot Thymeleaf Multipart文件上传(Spring-boot Thymeleaf Multipart file upload)

我正在尝试创建一个页面,允许用户选择要上传到我的SpringMVC控制器的文件。

这是我的控制器:

@RestController
public class CustomerDataController {

 @RequestMapping(value = "/customerFile", method = RequestMethod.POST)
 public @ResponseBody String handleFileUpload(@RequestParam("myFile") MultipartFile file) {
      if ( !file.isEmpty() ) {
          String name = file.getName();
          try {
              byte[] bytes = file.getBytes();
               BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream( new File( name + "-uploaded" ) ) );
              stream.write( bytes );
              stream.close();
              return "You successfully uploaded " + name + " into " + name + "-uploaded !";
           catch ( Exception e ) {
                return "You failed to upload " + name + " => " + e.getMessage();
           }
      } else {
           return "The selected file was empty and could not be uploaded.";
      }
  }

我的upload.html表单有:

 <form action="upload" th:action="@{/customerFile}" method="post" enctype="multipart/form-data">
      <input type="file" name="myFile" />
      <input type="submit" />
 </form>

我也尝试过使用标准(非Thymeleaf形式):

 <form method="post" action="/customerFile" enctype="multipart/form-data">
      <input type="file" name="file"/>
      <input type="submit"/>
 </form>

不确定它是否相关但我有以下配置:

 @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       ...
        registry.addViewController( "/upload" ).setViewName( "upload" );
    }

@Bean
    MultipartConfigElement multipartConfigElement() {
        MultiPartConfigFactory factory = new MultiPartConfigFactory();
        factory.setMaxFileSize("512KB");
        factory.setMaxRequestSize("512KB");
        return factory.createMultipartConfig();
    }

我在build.gradle中有以下内容:apply plugin:'java'

apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'jacoco'
apply plugin: 'war'

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-data-jpa:1.0.0.RC4")
    compile("org.springframework:spring-orm:4.0.0.RC1")
    compile("org.hibernate:hibernate-entitymanager:4.2.1.Final")
    compile("com.h2database:h2:1.3.172")
    compile("joda-time:joda-time:2.3")
    compile("org.thymeleaf:thymeleaf-spring4")
    compile("org.codehaus.groovy.modules.http-builder:http-builder:0.7.1")
    compile('org.codehaus.groovy:groovy-all:2.2.1')
    compile('org.jadira.usertype:usertype.jodatime:2.0.1')

    testCompile('org.spockframework:spock-core:0.7-groovy-2.0') {
        exclude group: 'org.codehaus.groovy', module: 'groovy-all'
    }
    testCompile('org.codehaus.groovy.modules.http-builder:http-builder:0.7+')
    testCompile("junit:junit")
}

我正在运行嵌入式Tomcat,通过以下方式启动:

public static void main(String[] args) {
        ApplicationContext ofac = SpringApplication.run( OFAC.class, args );
}

当我单击提交按钮时,我在控制器中看不到请求,但我在浏览器中看到以下内容:

HTTP Status 400 - Required MultipartFile parameter 'myFile' is not present

type Status report

message Required MultipartFile parameter 'myFile' is not present

description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.52

以下是Firebug告诉我有关请求的内容:

connection  close
Content-Language    en
Content-Length  1080
Content-Type    text/html;charset=utf-8
Date    Mon, 24 Mar 2014 17:09:55 GMT
Server  Apache-Coyote/1.1
Request Headersview source
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  JSESSIONID=86768954CD2877A7D78535E26CFFB8DA
DNT 1
Host    localhost:9001
Referer http://localhost:9001/upload

I am trying to create a page that allows a user to select a file to be uploaded to my SpringMVC Controller.

Here is my controller:

@RestController
public class CustomerDataController {

 @RequestMapping(value = "/customerFile", method = RequestMethod.POST)
 public @ResponseBody String handleFileUpload(@RequestParam("myFile") MultipartFile file) {
      if ( !file.isEmpty() ) {
          String name = file.getName();
          try {
              byte[] bytes = file.getBytes();
               BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream( new File( name + "-uploaded" ) ) );
              stream.write( bytes );
              stream.close();
              return "You successfully uploaded " + name + " into " + name + "-uploaded !";
           catch ( Exception e ) {
                return "You failed to upload " + name + " => " + e.getMessage();
           }
      } else {
           return "The selected file was empty and could not be uploaded.";
      }
  }

And my upload.html form has:

 <form action="upload" th:action="@{/customerFile}" method="post" enctype="multipart/form-data">
      <input type="file" name="myFile" />
      <input type="submit" />
 </form>

I have also tried using a standard (non Thymeleaf form):

 <form method="post" action="/customerFile" enctype="multipart/form-data">
      <input type="file" name="file"/>
      <input type="submit"/>
 </form>

Not sure if it's relevant but I have the following configuration:

 @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       ...
        registry.addViewController( "/upload" ).setViewName( "upload" );
    }

@Bean
    MultipartConfigElement multipartConfigElement() {
        MultiPartConfigFactory factory = new MultiPartConfigFactory();
        factory.setMaxFileSize("512KB");
        factory.setMaxRequestSize("512KB");
        return factory.createMultipartConfig();
    }

I have the following in my build.gradle: apply plugin: 'java'

apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'jacoco'
apply plugin: 'war'

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-data-jpa:1.0.0.RC4")
    compile("org.springframework:spring-orm:4.0.0.RC1")
    compile("org.hibernate:hibernate-entitymanager:4.2.1.Final")
    compile("com.h2database:h2:1.3.172")
    compile("joda-time:joda-time:2.3")
    compile("org.thymeleaf:thymeleaf-spring4")
    compile("org.codehaus.groovy.modules.http-builder:http-builder:0.7.1")
    compile('org.codehaus.groovy:groovy-all:2.2.1')
    compile('org.jadira.usertype:usertype.jodatime:2.0.1')

    testCompile('org.spockframework:spock-core:0.7-groovy-2.0') {
        exclude group: 'org.codehaus.groovy', module: 'groovy-all'
    }
    testCompile('org.codehaus.groovy.modules.http-builder:http-builder:0.7+')
    testCompile("junit:junit")
}

I am running embedded Tomcat, launched via:

public static void main(String[] args) {
        ApplicationContext ofac = SpringApplication.run( OFAC.class, args );
}

When I click the submit button, I don't see a request in my controller but I get a the following in my browser:

HTTP Status 400 - Required MultipartFile parameter 'myFile' is not present

type Status report

message Required MultipartFile parameter 'myFile' is not present

description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.52

Here is what Firebug tells me about the request:

connection  close
Content-Language    en
Content-Length  1080
Content-Type    text/html;charset=utf-8
Date    Mon, 24 Mar 2014 17:09:55 GMT
Server  Apache-Coyote/1.1
Request Headersview source
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  JSESSIONID=86768954CD2877A7D78535E26CFFB8DA
DNT 1
Host    localhost:9001
Referer http://localhost:9001/upload

原文:https://stackoverflow.com/questions/22598968
更新时间:2022-06-04 09:06

最满意答案

我会说$pid也包含你脚本的pid。 你可以过滤掉它:

script_pid=$$
pid=$(ps -ef | grep temp_tool | grep -Ev "grep|$script_pid" | awk '{print $2}')

虽然你想要命令temp_tool我会建议:

ps -C temp_tool -o pid

而不是ps -ef | grep ... ps -ef | grep ...


I would say $pid also contains the pid of your script. You can filter it out:

script_pid=$$
pid=$(ps -ef | grep temp_tool | grep -Ev "grep|$script_pid" | awk '{print $2}')

Though if you want the pids of the command temp_tool I would suggest this:

ps -C temp_tool -o pid

Instead of the ps -ef | grep ...

相关问答

更多
  • 您可以开始查看PHP手册: 系统程序执行 但像sdleihssirhc提到的,注意这是非常危险的,你不应该允许一切都被执行! 如果你仍然想这样做,为了得到shell的输出,只需使用 EXEC shell的输出将在第二个参数中传递。 例如: exec('ls -la', $outputArray); print_r($outputArray); You could start looking at the php manual: System program execution But like sdlei ...
  • 我可以在Ubuntu VM中重现此问题,但不能在OEL VM上重现此问题。 不同的是,在Ubuntu上, command-not-found安装包command-not-found ,它提供了python脚本/usr/lib/command-not-found 。 此脚本负责退出shell。 在/etc/bash.bashrc ,有一个函数command-not-found_handle ,它执行/usr/lib/command-not-found 。 因此,当我们尝试执行这样的命令时,终端退出。 当我发表 ...
  • 好的,自己解决了 def sout = new StringBuilder(), serr = new StringBuilder() def proc = 'ls /badDir'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println "out> $sout err> $serr" 显示: out> err> ls: cannot access /badDir: No such file or d ...
  • 如果您不希望系统运行shell命令,请不要使用system因为这就是它要执行的操作。 如果你正在谈论的只是运行你想运行的命令,那么有很多种方法。 在掌握Perl的安全性章节中,我会谈论其中的一些。 但是,您必须澄清您试图避免的问题。 If you don't want system to run shell commands, don't use system because that's what it is there to do. If you're talking about running onl ...
  • 正如其他人所指出的那样,您可以为应用程序提供背景(例如,男人bash'工作控制')。 此外,您可以使用内建等待以后明确地等待后台作业: ./application & echo doing some more work wait # wait for background jobs to complete echo application has finished 您应该像往常一样阅读man pages和bash帮助以获取更多详细信息: http://unixhelp.ed.ac.uk/CGI ...
  • 我会说$pid也包含你脚本的pid。 你可以过滤掉它: script_pid=$$ pid=$(ps -ef | grep temp_tool | grep -Ev "grep|$script_pid" | awk '{print $2}') 虽然你想要命令temp_tool我会建议: ps -C temp_tool -o pid 而不是ps -ef | grep ... ps -ef | grep ... I would say $pid also contains the pid of your s ...
  • 从文档中 , firebase init命令只创建文件firebase.json 。 为什么不以交互方式进行,然后再手动生成JSON呢? 即如果你这样做并且它产生了 { "firebase": "myfirebase", "public": "app", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } 那你就可以做到 $ echo $'{\n "firebase": "myfirebas ...
  • 你是否可以在后台启动tcpdump命令并在一段固定的时间后终止它? 比如跑 (tcpdump (options) | fgrep (options) > file) & 然后得到过程的pid并等待一段时间, pid=$! sleep 60 最后杀死命令并解析输出 kill -9 $pid sed (options) file | awk (options) rm file 更新 如果你真的想让Ctrl-P停止tcpdump ,那么trap就是你要走的路。 但是,在执行trapped命令后,您将始终 ...
  • shell基本上执行以下操作: 从标准输入读取一行 解析该行以制作单词列表 叉子 然后shell(父进程)等待直到子进程结束,而子进程执行以执行从输入行提取的单词列表所代表的命令的代码。 然后shell在步骤1重新启动。 首先构造一个非常简单的shell。 A shell basically does the following : reads a line from stdin parses that line to make a list of words forks then the shell (p ...
  • 我建议在脚本中进行以下更改以达到所需要求。 看起来你需要某种能够捕获这些命令而不让命令执行的函数。 Shell脚本可以通过实现trap的使用来实现这种功能。 您可以在脚本中进行如下更改: PR=`basename $0` cdt=`date +'%H:%M:%S %d/%m/%Y'` cd $HOME/myprogram #Add these two lines in the code for catching exit commands trap '' 20 trap ' ' INT jav ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。