如何从MultipartHttpServletRequest中写入文件,使用Java。

huangapple go评论63阅读模式
英文:

How to write the file from MultipartHttpServletRequest in java

问题

以下是您提供的代码的中文翻译:

作为我的后端团队将发送zip文件如何在JavaEclipse中接收文件并存储到项目位置

我尝试过一些代码使用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 = &quot;/retrieveBillerByFile1&quot;, method = RequestMethod.POST)
public @ResponseBody void retrieveBillerByFile1(@RequestPart MultipartHttpServletRequest  request) throws Exception 
{
System.out.println(&quot;RESPONSEEEE**&quot;+request);
Iterator&lt;String&gt; itrator = request.getFileNames();
System.out.println(&quot;File Name:&quot; + request.getFileNames());
MultipartFile multiFile = request.getFile(itrator.next());
System.out.println(&quot;itrator.next()&quot; + itrator.next());
try {
// just to show that we have actually received the file
System.out.println(&quot;File Length:&quot; + multiFile.getBytes().length);
String name = multiFile.getOriginalFilename();
System.out.println(&quot;name&quot; + name);
System.out.println(&quot;multiFile.getBytes()&quot; + multiFile.getBytes());
BufferedWriter w = Files.newBufferedWriter(Paths.get(&quot;D:\\cedge_uat\\&quot; + name ));
w.write(new String(multiFile.getBytes()));
w.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(&quot;Error while loading the file&quot;);
}
}

Another Way I have tried but fileItem getting as null

@RequestMapping(value = &quot;/retrieveBillerByFile&quot;, method = RequestMethod.POST)
public @ResponseBody void retrieveBillerByFile(@RequestPart HttpServletRequest request,
HttpServletResponse response) throws Exception 
{
System.out.println(&quot;RESPONSEEEE**&quot;+request);
System.out.println(&quot;request**&quot;+request);
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
System.out.println(&quot;Form must has enctype=multipart/form-data.**&quot;);
// if not, we stop here
PrintWriter writer = response.getWriter();
writer.println(&quot;Error: Form must has enctype=multipart/form-data.&quot;);
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(&quot;java.io.tmpdir&quot;)));
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&#39;s directory
//  String uploadPath = servletContext.getRealPath(&quot;&quot;)+ File.separator + UPLOAD_DIRECTORY;
String uploadPath = servletContext.getRealPath(&quot;/WEB-INF/xml&quot;) + 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(&quot;uploadPath\n&quot;+ uploadPath);
try {
// parses the request&#39;s content to extract file data
@SuppressWarnings(&quot;unchecked&quot;)
List&lt;FileItem&gt; formItems = upload.parseRequest(request);
System.out.println(&quot;formItems**&quot;+formItems);
if (formItems != null &amp;&amp; formItems.size() &gt; 0) {
// iterates over form&#39;s fields
for (FileItem item : formItems) {
System.out.println(&quot;item**&quot;+item);
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println(&quot;fileName**&quot;+fileName);
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
System.out.println(&quot;success&quot;);
request.setAttribute(&quot;message&quot;,
&quot;Upload has been done successfully!&quot;);
}
}
}
} catch (Exception ex) {
System.out.println(&quot;exception&quot;+ ex.getMessage());
request.setAttribute(&quot;message&quot;,
&quot;There was an error: &quot; + 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

huangapple
  • 本文由 发表于 2020年10月16日 17:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64386371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定