0
我是新的彈簧,我想在服務器上傳文件。但它沒有保存該特定格式的文件..幫助我....如何在服務器上使用彈簧上傳文件
這裏是我的jsp頁面。
<html>
<head>
<title>Upload File Request Page</title>
</head>
<body>
<form method="POST" action="uploadFile" enctype="multipart/form-data">
File to upload: <input type="file" name="file"><br><br>
<!-- Name: <input type="text" name="file"><br> <br> -->
<input type="submit" value="Upload"> Press here to upload the file!
</form>
</body>
</html>
和控制器文件。
public class FileUploadController
{
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
/**
* Upload single file using Spring Controller
*/
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String upload(Locale locale, Model model)
{
logger.info("upload");
return "upload";
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam(value = "name", required = false) String name,
@RequestParam("file") MultipartFile file)
{
if (!file.isEmpty())
{
try
{
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles/abc");
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(name));
stream.write(bytes);
stream.close();
logger.info("Server File Location=" + serverFile.getAbsolutePath());
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.";
}
}