Я разрешаю пользователю загружать файл xls. При нажатии кнопки я хочу передать имя файла контроллеру и прочитать его.
Вот код jsp:
function uploadTemplate()
{
//window.location.href = "uploaduserdashboardreqmultiple";
String fileName = document.getElementById("filename").value;
document.uploadRequest.action = "uploadFile?filename"+filename;
document.uploadRequest.submit();
}
<form:form action="" method="POST" modelAttribute="uploadFile" name="uploadRequest" enctype="multipart/form-data">
<div align="center" style="margin-bottom: 10px;">
<button onClick = "downloadTemplate()" style="width:250px" type="submit" class="admin_search_btn"><spring:message code="lblDownloadXls"></spring:message></button>
</div>
<div align="center" style="margin-bottom: 10px;" >
<form:input path="fileName" style="width:200px" id="filename" class="admin_search_btn" type="file" />
<div align="center" style="margin-bottom: 10px;" >
<button onClick = "uploadTemplate()" type="submit" class="admin_search_btn"><spring:message code="lblSubmit"></spring:message></button>
<button type="submit" class="admin_search_btn">Cancel</button>
</div>
</div>
</form:form>
При нажатии кнопки я вызывал функцию и передавал имя файла контроллеру.
контроллер:
@RequestMapping(value = "/uploadFile")
public
String uploadFileHandler(@ModelAttribute UploadFile uploadFile,
@RequestParam("filename") String name
/* @RequestParam("file") MultipartFile file*/) {
if (!name.isEmpty()) {
try {
byte[] bytes = name.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
return "You successfully uploaded file=" + name;
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
Я не ошибаюсь. Но когда я проверяю режим отладки, он отображает значение null
для uploadFile
и filename
Я что-то делаю неправильно?
Вы можете попробовать с MultipartFile#getOriginalFilename()
Модель/командный класс
private CommonsMultipartFile imageFile;
JSP/HTML:
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<sf:input path="imageFile" type="file" />
Взгляните на полный пример 1 и пример2
Согласно вашему последнему комментарию, попробуйте
Ниже приведен код с весны в действии 3-е издание - глава 7
У меня есть образец проекта, который используется для загрузки изображения на сервере. Это всего лишь часть страницы registration
моего образца проекта.
JSP:
<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<sf:form method="POST" modelAttribute="spitter"
enctype="multipart/form-data">
<sf:input path="imageFile" type="file" />
</sf:form>
контроллер:
// first request
@RequestMapping("/signup")
public String showSpitterForm(Model model) {
model.addAttribute("spitter", new SpitterModel());
return "signup";
}
/*
* Form submission for spitter registration
*/
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String addSpitterFromForm(
@Valid @ModelAttribute("spitter") SpitterModel spitterModel,
BindingResult bindingResult, HttpSession session,
HttpServletRequest request) {
if (bindingResult.hasErrors()) {
return "signup";
} else {
saveSpitter(spitterModel, session
.getServletContext().getRealPath("/resources/upload"));
return "redirect:list";
}
}
SpitterModel:
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class SpitterModel {
private CommonsMultipartFile imageFile;
public CommonsMultipartFile getImageFile() {
return imageFile;
}
public void setImageFile(CommonsMultipartFile imageFile) {
this.imageFile = imageFile;
}
}
Метод saveSpitter
MultipartFile file = model.getImageFile();
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fullyFileName);
int readBytes = 0;
byte[] buffer = new byte[1024 * 50];
while ((readBytes = inputStream.read(buffer, 0, 1024 * 50)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
файл конфигурации пружины:
<!-- Configure the multipart resolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
Я думаю, вам не хватает добавить компонент multipartResolver в ваш servlet-context.xml file-
<!-- Multipart Resolver -->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="5000000" />
<!-- Max size in bytes. -->
<beans:property name="maxInMemorySize" value="4096" />
<!-- Max size in memory. -->
</beans:bean>
и добавьте заданную зависимость в pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
Вместо вызова функции uploadTemplate() при отправке кнопки установите атрибут action в теге формы в uploadFile, как указано below-
<form:form action="uploadFile" method="POST" modelAttribute="uploadFile" name="uploadRequest" enctype="multipart/form-data">
null
? Это не должно быть возможно.