作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我一直在将 spring 集成到应用程序中,并且必须重新从表单上传文件。我知道 Spring MVC 必须提供什么,以及我需要做什么来配置我的 Controller 以能够上传文件。我已经阅读了足够多的教程来做到这一点,但是这些教程都没有解释正确的/最佳实践方法,即在你拥有文件后如何/做什么来实际处理文件。下面是一些类似于 Spring MVC Docs 中关于处理文件上传的代码的代码,可以在
找到 Spring MVC File Upload
在下面的示例中,您可以看到他们向您展示了获取文件所需的所有操作,但他们只是说 Do Something with the bean
我查看了许多教程,它们似乎都让我明白了这一点,但我真正想知道的是处理文件的最佳方法。一旦我现在有了一个文件,将这个文件保存到服务器上的目录的最佳方法是什么?有人可以帮我吗?谢谢
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
let's see if there's content there
byte[] file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything
}
//do something with the bean
return super.onSubmit(request, response, command, errors);
}
最佳答案
这是我在上传时更喜欢的方式。我认为让 spring 来处理文件保存是最好的方法。 Spring 使用它的 MultipartFile.transferTo(File dest)
函数来实现。
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/upload")
public class UploadController {
@ResponseBody
@RequestMapping(value = "/save")
public String handleUpload(
@RequestParam(value = "file", required = false) MultipartFile multipartFile,
HttpServletResponse httpServletResponse) {
String orgName = multipartFile.getOriginalFilename();
String filePath = "/my_uploads/" + orgName;
File dest = new File(filePath);
try {
multipartFile.transferTo(dest);
} catch (IllegalStateException e) {
e.printStackTrace();
return "File uploaded failed:" + orgName;
} catch (IOException e) {
e.printStackTrace();
return "File uploaded failed:" + orgName;
}
return "File uploaded:" + orgName;
}
}
关于java - Spring MVC 文件上传帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3577942/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!