将上传的文件保存在服务器上
问题描述:
我从系统上载了一个文件,我已将该文件转换为字节.现在,我想将该文件保存在服务器上.我怎样才能做到这一点.我已经在互联网上搜索了,但一无所获.这个问题有什么解决办法吗? 我正在使用JSP上传文件.
I have uploaded a file from my system, I have converted the file in bytes. Now I want to save that file at server. How can I do this. I have searched through the internet but found nothing. Is there any solution of this problem? I am uploading file using JSP.
答
如果您谈论的是UploadedFile,以下是我在进行大量互联网搜索后如何实现的目标:
If you are talking about UploadedFile, here is how I achieved this after a huge internet search:
/**
* Save uploaded file to server
* @param path Location of the server to save file
* @param uploadedFile Current uploaded file
*/
public static void saveUploadedFile(String path, UploadedFile uploadedFile) {
try {
//First, Generate file to make directories
String savedFileName = path + "/" + uploadedFile.getFileName();
File fileToSave = new File(savedFileName);
fileToSave.getParentFile().mkdirs();
fileToSave.delete();
//Generate path file to copy file
Path folder = Paths.get(savedFileName);
Path fileToSavePath = Files.createFile(folder);
//Copy file to server
InputStream input = uploadedFile.getInputstream();
Files.copy(input, fileToSavePath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
}
}