java - 你如何从并使用servlet在另一个jsp页面上编写/显示它?
问题描述
我有一个接受图像的网页<input type="file" name="imgFile" accept="image/*" />
我希望完成的是,当我提交表单时,图像会显示在另一个页面上,.jsp
确切地说,是在 servlet 的帮助下。
如果我不能完全做到这一点(将图像直接从一个 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
推荐阅读
- python - Flask SocketIO raises a ValueError
- c# - 请求正文已加密
- ruby-on-rails - 如何在表格中制作表格以在rails中使用选择?
- android - 如何像 Android 消息应用一样自定义浮动按钮?
- css - 将输入焦点扩展到图标,以便可点击
- javascript - 如何在 google app maker sql 中更新另一个模型(触发器)的记录?
- java - 为什么 Selenium Webdriver 每次运行脚本都会打开新窗口以及如何修复它?
- android - 在静态快捷方式中实现 Share App Facility
- html - 表格每次在最后一个对象 HTML 下移动
- oracle - Oracle 存储过程抛出“没有足够的值”错误