The*_*boy 21 java spring file-upload spring-mvc
我一直在将spring集成到一个应用程序中,并且必须从表单重做文件上传.我知道Spring MVC提供了什么以及我需要做些什么来配置我的控制器才能上传文件.我已经阅读了足够的教程以便能够做到这一点,但是这些教程没有解释的是关于如何/一旦你拥有文件后如何实际处理文件的正确/最佳实践方法.下面是一些代码,类似于Spring MVC Docs上关于处理文件上传的代码,可以在
Spring MVC File Upload上找到
在下面的示例中,您可以看到它们向您显示了获取文件的所有操作,但它们只是说使用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);
}
Run Code Online (Sandbox Code Playgroud)
Fer*_*büz 20
这是我在上传时的偏好.我认为让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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20477 次 |
最近记录: |