我有一个网页可以通过<input type="file" name="imgFile" accept="image/*" />
接受图像
我希望完成的工作是,当我提交表单时,在servlet的帮助下,图像显示在另一页上,确切地说是.jsp
。
如果无法完全做到这一点(将图像从一个jsp直接传递到另一个jsp),如何通过在磁盘上本地写入文件并通过<img>
标签在jsp文件中读取该文件来实现呢?该文件可以存储在磁盘上的任何位置(例如C:\ Sample),所以放在我的位置并不重要。谢谢!
这里有一个代码示例,该示例从表单上载图像。请根据需要修改操作和属性。
<form:form modelAttribute="modelClass" action="save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<form:input type="file" path="productLandscapeImage" class="form-control" name="productLandscapeImage" title="Image" value=""/>
<form:errors path="productLandscapeImage" cssClass="error-tip" element="div" />
</div>
</form:form>
模型modelClass
必须包含属性
private MultipartFile productLandscapeImage;
在您的控制器类别中
@RequestMapping(value = { "form/save" }, method = RequestMethod.POST)
public String saveProduct(@Valid @ModelAttribute("modelClass") ModelClass modelClass
BindingResult bindingResult, Model model, HttpServletRequest httpServletRequest) {
uploadImages(modelClass, httpServletRequest);
}
private void uploadImages(ModelClass modelClass, HttpServletRequest httpServletRequest) {
if (modelClass.getProductLandscapeImage() != null
&& !modelClass.getProductLandscapeImage().getOriginalFilename().isEmpty()) {
String realPath = httpServletRequest.getSession().getServletContext().getRealPath("/resources/images/categories/");
if (!new File(realPath).exists()) {
new File(realPath).mkdirs();
}
try {
modelClass.getProductLandscapeImage().transferTo(new File(realPath + ".jpg"));
} catch (IllegalStateException | IOException e) {
// log error
}
}
}
在您的DispatcherServletInitializer类中添加以下方法
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
/**
* maxFileSize: Maximum Size of the file to be uploaded
* maxRequestSize: Maximum Size of the multipart/form-data request
* fileSizeThreshold: Size threshold after which the file will be written to disk
*
* The Size are in bytes
* 1024 * 1024 * 1 = 1MB
* 1024 * 1024 * 2 = 2MB
* 1024 * 1024 * 4 = 4MB
*/
@Override
protected void customizeRegistration(Dynamic registration) {
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/", 2097152, 8388608, 1048576);
registration.setMultipartConfig(multipartConfigElement);
}
}
在您的Web Config类中添加以下bean
@Configuration
@ComponentScan(basePackages = {"com.package"})
@EnableWebMvc
public class SpringWebConfiguration implements WebMvcConfigurer{
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
请查看此链接以获取完整代码Full Code Git