英文:
How to write the file from MultipartHttpServletRequest in java
问题
以下是您提供的代码的中文翻译:
作为我的后端团队将发送zip文件,如何在Java(Eclipse)中接收文件并存储到项目位置?
我尝试过一些代码,使用MultipartHttpServletRequest并获取多部分长度以及创建zip文件夹,但是在尝试提取时显示无效。然后如何将其写入文件中。请帮助我。
@RequestMapping(value = "/retrieveBillerByFile1", method = RequestMethod.POST)
public @ResponseBody void retrieveBillerByFile1(@RequestPart MultipartHttpServletRequest request) throws Exception
{
System.out.println("RESPONSEEEE**" + request);
Iterator<String> itrator = request.getFileNames();
System.out.println("文件名:" + request.getFileNames());
MultipartFile multiFile = request.getFile(itrator.next());
System.out.println("itrator.next()" + itrator.next());
try {
// 仅仅为了展示我们已经接收到了文件
System.out.println("文件长度:" + multiFile.getBytes().length);
String name = multiFile.getOriginalFilename();
System.out.println("文件名" + name);
System.out.println("multiFile.getBytes()" + multiFile.getBytes());
BufferedWriter w = Files.newBufferedWriter(Paths.get("D:\\cedge_uat\\" + name));
w.write(new String(multiFile.getBytes()));
w.flush();
} catch (Exception e) {
// 处理文件加载时的错误
e.printStackTrace();
throw new Exception("加载文件时出错");
}
}
另一种方式我尝试过,但是fileItem为null。
@RequestMapping(value = "/retrieveBillerByFile", method = RequestMethod.POST)
public @ResponseBody void retrieveBillerByFile(@RequestPart HttpServletRequest request,
HttpServletResponse response) throws Exception
{
System.out.println("RESPONSEEEE**" + request);
System.out.println("request**" + request);
// 检查请求是否包含上传文件
if (!ServletFileUpload.isMultipartContent(request)) {
System.out.println("表单必须有enctype=multipart/form-data。");
// 如果没有,就在这里停止
PrintWriter writer = response.getWriter();
writer.println("错误:表单必须有enctype=multipart/form-data。");
writer.flush();
return;
}
// 配置上传设置
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存阈值 - 超过此阈值的文件将存储在磁盘上
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置用于存储文件的临时位置
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件的最大大小
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置请求的最大大小(包括文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 构造用于存储上传文件的目录路径
// 此路径相对于应用程序的目录
String uploadPath = servletContext.getRealPath("/WEB-INF/xml") + File.separator + UPLOAD_DIRECTORY;
// 如果目录不存在,则创建目录
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.println("uploadPath\n" + uploadPath);
try {
// 解析请求内容以提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
System.out.println("formItems**" + formItems);
if (formItems != null && formItems.size() > 0) {
// 遍历表单字段
for (FileItem item : formItems) {
System.out.println("item**" + item);
// 仅处理不是表单字段的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println("fileName**" + fileName);
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 将文件保存到磁盘上
item.write(storeFile);
System.out.println("成功");
request.setAttribute("message",
"上传成功!");
}
}
}
} catch (Exception ex) {
System.out.println("异常" + ex.getMessage());
request.setAttribute("message",
"发生错误:" + ex.getMessage());
}
}
希望这对您有所帮助。如果您需要进一步的协助,请随时告诉我。
英文:
As my backend end team will send the zip file , how to receive the file and store into the project location in java(eclipse)
As im tried some code using MultipartHttpServletRequest and getting multipart length and zip folder also created but when unable to extract that showing invalid. then how to write into the file . Please help me
@RequestMapping(value = "/retrieveBillerByFile1", method = RequestMethod.POST)
public @ResponseBody void retrieveBillerByFile1(@RequestPart MultipartHttpServletRequest request) throws Exception
{
System.out.println("RESPONSEEEE**"+request);
Iterator<String> itrator = request.getFileNames();
System.out.println("File Name:" + request.getFileNames());
MultipartFile multiFile = request.getFile(itrator.next());
System.out.println("itrator.next()" + itrator.next());
try {
// just to show that we have actually received the file
System.out.println("File Length:" + multiFile.getBytes().length);
String name = multiFile.getOriginalFilename();
System.out.println("name" + name);
System.out.println("multiFile.getBytes()" + multiFile.getBytes());
BufferedWriter w = Files.newBufferedWriter(Paths.get("D:\\cedge_uat\\" + name ));
w.write(new String(multiFile.getBytes()));
w.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("Error while loading the file");
}
}
Another Way I have tried but fileItem getting as null
@RequestMapping(value = "/retrieveBillerByFile", method = RequestMethod.POST)
public @ResponseBody void retrieveBillerByFile(@RequestPart HttpServletRequest request,
HttpServletResponse response) throws Exception
{
System.out.println("RESPONSEEEE**"+request);
System.out.println("request**"+request);
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
System.out.println("Form must has enctype=multipart/form-data.**");
// if not, we stop here
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
// sets memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(MEMORY_THRESHOLD);
// sets temporary location to store files
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// sets maximum size of upload file
upload.setFileSizeMax(MAX_FILE_SIZE);
// sets maximum size of request (include file + form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
// this path is relative to application's directory
// String uploadPath = servletContext.getRealPath("")+ File.separator + UPLOAD_DIRECTORY;
String uploadPath = servletContext.getRealPath("/WEB-INF/xml") + File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.println("uploadPath\n"+ uploadPath);
try {
// parses the request's content to extract file data
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
System.out.println("formItems**"+formItems);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
System.out.println("item**"+item);
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println("fileName**"+fileName);
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
System.out.println("success");
request.setAttribute("message",
"Upload has been done successfully!");
}
}
}
} catch (Exception ex) {
System.out.println("exception"+ ex.getMessage());
request.setAttribute("message",
"There was an error: " + ex.getMessage());
}
}
答案1
得分: 1
你可以在方法中添加另一个参数--
@RequestParam MultipartFile file
这样你的方法将会是--
public @ResponseBody void retrieveBillerByFile1(@RequestParam MultipartFile file, @RequestPart MultipartHttpServletRequest request) throws Exception
然后使用Java文件API处理文件。
英文:
You can add another param in the method --
@RequestParam MultipartFile file
so your method will be --
public @ResponseBody void retrieveBillerByFile1(@RequestParam MultipartFile file, @RequestPart MultipartHttpServletRequest request) throws Exception
And then manipulate the file using java file apis
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论