我正在使用 spring MVC 和 jquery 上传文件。在我的类方法中我写了
@RequestMapping(value="attachFile", method=RequestMethod.POST)
public @ResponseBody List<FileAttachment> upload(
@RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpSession session) {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
//Save the file to a temporary location
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
fileName = realContextPath +"/images/"+file.getOriginalFilename();
//File dest = new File(fileName);
try {
//file.transferTo(dest);
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fileName);
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
它正确上传我正在使用的文件
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath("/");
获取路径。我的第一个问题是,这是获取路径的正确方法吗?它将文件存储在 工作区/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images
当我尝试使用以下代码在我的 jsp 页面上显示此图像时
<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />
它不显示图像,它生成以下 html
<img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">
我做的事情正确吗?在我的项目中,我每天必须上传大量文件。
如果您需要其他信息来理解我的问题,请告诉我
最佳答案
如果您通过绝对路径(例如 C:\images\
)而不是相对路径(您的方法)将文件上传到某个目录中,效果会更好。通常,Web 应用程序在生产环境中运行在 Linux Mathines 上,并且最好将保存路径配置为可配置。
创建一些应用程序属性,用于保存文件的保存路径(在 xml 或属性文件中)。
关于java - 使用 Spring MVC 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12076818/