upload file

本文介绍了一个使用Struts2框架实现文件上传的例子。通过ServletFileUpload组件解析HTTP请求中的文件,设置文件大小限制,并将文件保存到指定路径。示例中还包括了JSP页面代码。
  1.  //服务器断
  2. private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)   
  3.     {   
  4.         // 操作文件   
  5.         response.setContentType("text/html; charset=UTF-8");   
  6.         DiskFileItemFactory factory = new DiskFileItemFactory();   
  7.         factory.setSizeThreshold(1024 * 4);   
  8.         ServletFileUpload upload = new ServletFileUpload(factory);   
  9.         upload.setFileSizeMax(maxPostSize);   
  10.         logger("request========" + ObjectUtils.toString(request));   
  11.         List fileItems = null;   
  12.         try {   
  13.             fileItems = upload.parseRequest(request);   
  14.             logger("============" + ObjectUtils.toString(fileItems));   
  15.             Iterator iter = fileItems.iterator();   
  16.             while (iter.hasNext()) {   
  17.                 FileItem item = (FileItem) iter.next();   
  18.                 log(item.toString());   
  19.                 if (!item.isFormField()) {   
  20.                     String name = item.getName();   
  21.                     logger("上传的文件名 = " + name);   
  22.                     try {   
  23.                         item.write(new File(uploadPath + name));   
  24.                     } catch (Exception ex) {   
  25.                         logger(ex.getMessage());   
  26.                     }   
  27.                 }   
  28.             }   
  29.         } catch (FileUploadException ex1) {   
  30.             logger("FileUploadException->" + ex1.getMessage());   
  31.         }   
  32.     }   

 

页面:

 

<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
   
< title > Struts 2 File Upload </ title >
</ head >
< body >
   
< s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >
       
< s:file name ="myFile" label ="Image File" />
       
< s:textfield name ="caption" label ="Caption" />        
       
< s:submit />
   
</ s:form >
</ body >
</ html >

### 在 GraphQL 中实现文件上传功能 GraphQL 本身并不直接支持文件上传,因为其设计初衷是处理结构化数据查询和变更。然而,通过结合一些额外的技术和约定,可以在 GraphQL 中实现文件上传功能。以下是实现文件上传功能的详细方法: #### 1. 使用 `graphql-upload` 库 `graphql-upload` 是一个广泛使用的库,用于在 GraphQL 中实现文件上传功能。它基于 Apollo Server 和 Express,并允许开发者轻松地处理文件上传。 以下是一个简单的实现示例: ```javascript // 安装依赖 npm install graphql-upload apollo-server-express express // 引入必要的模块 const { ApolloServer, gql } = require('apollo-server-express'); const { graphqlUploadExpress } = require('graphql-upload'); // 启用文件上传中间件 const app = require('express')(); graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 })(app); // 定义 GraphQL 类型 const typeDefs = gql` scalar Upload type File { filename: String! mimetype: String! encoding: String! } type Query { uploads: [File] } type Mutation { uploadFile(file: Upload!): File! } `; // 定义解析器 const resolvers = { Query: { uploads: () => [], }, Mutation: { uploadFile: async (_, { file }) => { const { createReadStream, filename, mimetype, encoding } = await file; const stream = createReadStream(); const outputPath = `./uploads/${filename}`; // 将文件保存到服务器 const { promisify } = require('util'); const pipeline = promisify(require('stream').pipeline); await pipeline(stream, require('fs').createWriteStream(outputPath)); return { filename, mimetype, encoding }; }, }, }; // 创建 Apollo Server 实例 const server = new ApolloServer({ typeDefs, resolvers }); server.applyMiddleware({ app }); // 启动服务器 app.listen({ port: 4000 }, () => console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`) ); ``` 上述代码实现了以下功能: - 定义了一个 `Upload` 标量类型,用于表示文件上传[^1]。 - 提供了一个 `uploadFile` 变更操作,用于接收文件并将其保存到服务器上的指定目录[^2]。 #### 2. 文件上传的客户端实现 在客户端,可以使用 `graphql-request` 或其他 GraphQL 客户端库来上传文件。以下是一个使用 `graphql-request` 的示例: ```javascript const fs = require('fs'); const { request } = require('graphql-request'); const endpoint = 'http://localhost:4000/graphql'; const mutation = ` mutation UploadFile($file: Upload!) { uploadFile(file: $file) { filename mimetype encoding } } `; const variables = { file: fs.createReadStream('./example.txt'), }; request(endpoint, mutation, variables).then((data) => console.log(data)); ``` #### 3. 注意事项 - 确保服务器端启用了适当的文件大小限制和安全性检查,以防止恶意文件上传[^3]。 - 文件路径应动态生成,避免覆盖已有文件或引发安全问题[^4]。 - 如果需要上传多个文件,可以在变更操作中定义数组类型的 `Upload` 参数。 ### 结论 通过使用 `graphql-upload` 库,可以在 GraphQL 中轻松实现文件上传功能。该方法结合了 Apollo Server 和 Express,提供了灵活且强大的文件处理能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值