upload文件上传,保存为文件

本文介绍了一个使用 Vaadin 框架实现的文件上传组件,该组件支持自定义按钮文本,并能监听上传成功和失败的事件。文章详细展示了如何创建上传组件、设置回调方法以接收上传文件并将其显示出来。
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.OutputStream;  
  4. import com.vaadin.terminal.FileResource;  
  5. import com.vaadin.ui.*;  
  6. public class MyUploader extends CustomComponent  
  7.                         implements Upload.SucceededListener,  
  8.                                    Upload.FailedListener,  
  9.                                    Upload.Receiver {  
  10.   
  11.     Panel root;         // Root element for contained components.  
  12.     Panel imagePanel;   // Panel that contains the uploaded image.  
  13.     File  file;         // File to write to.  
  14.   
  15.     MyUploader() {  
  16.         root = new Panel("My Upload Component");  
  17.         setCompositionRoot(root);  
  18.   
  19.         // Create the Upload component.  
  20.         final Upload upload =  
  21.                 new Upload("Upload the file here"this);  
  22.   
  23.         // Use a custom button caption instead of plain "Upload".  
  24.         upload.setButtonCaption("Upload Now");  
  25.   
  26.         // Listen for events regarding the success of upload.  
  27.         upload.addListener((Upload.SucceededListener) this);  
  28.         upload.addListener((Upload.FailedListener) this);  
  29.   
  30.         root.addComponent(upload);  
  31.         root.addComponent(new Label("Click 'Browse' to "+  
  32.                 "select a file and then click 'Upload'."));  
  33.   
  34.         // Create a panel for displaying the uploaded image.  
  35.         imagePanel = new Panel("Uploaded image");  
  36.         imagePanel.addComponent(  
  37.                          new Label("No image uploaded yet"));  
  38.         root.addComponent(imagePanel);  
  39.     }  
  40.   
  41.     // Callback method to begin receiving the upload.  
  42.     public OutputStream receiveUpload(String filename,  
  43.                                       String MIMEType) {  
  44.         FileOutputStream fos = null// Output stream to write to  
  45.         file = new File("/tmp/uploads/" + filename);  
  46.         try {  
  47.             // Open the file for writing.  
  48.             fos = new FileOutputStream(file);  
  49.         } catch (final java.io.FileNotFoundException e) {  
  50.             // Error while opening the file. Not reported here.  
  51.             e.printStackTrace();  
  52.             return null;  
  53.         }  
  54.   
  55.         return fos; // Return the output stream to write to  
  56.     }  
  57.   
  58.     // This is called if the upload is finished.  
  59.     public void uploadSucceeded(Upload.SucceededEvent event) {  
  60.         // Log the upload on screen.  
  61.         root.addComponent(new Label("File " + event.getFilename()  
  62.                 + " of type '" + event.getMIMEType()  
  63.                 + "' uploaded."));  
  64.           
  65.         // Display the uploaded file in the image panel.  
  66.         final FileResource imageResource =  
  67.                 new FileResource(file, getApplication());  
  68.         imagePanel.removeAllComponents();  
  69.         imagePanel.addComponent(new Embedded("", imageResource));  
  70.     }  
  71.   
  72.     // This is called if the upload fails.  
  73.     public void uploadFailed(Upload.FailedEvent event) {  
  74.         // Log the failure on screen.  
  75.         root.addComponent(new Label("Uploading "  
  76.                 + event.getFilename() + " of type '"  
  77.                 + event.getMIMEType() + "' failed."));  
  78.     }  
  79. }  
### 使用 `el-upload` 组件上传前保存文件 为了在使用 `el-upload` 组件时,在上传之前保存文件,可以利用组件提供的事件钩子来处理文件。具体来说,可以通过监听文件列表改变的事件 (`change`) 或者自定义上传行为 (`beforeUpload`) 来捕获并保存文件。 #### 利用 `beforeUpload` 钩子提前处理文件 通过配置 `beforeUpload` 属性指定一个方法,该方法会在每次选择新文件准备上传之前被调用。这允许执行一些前置逻辑,比如验证文件大小、类型或是直接在此阶段将文件暂存起来[^3]。 ```javascript // JavaScript (Vue.js 方法内) handleBeforeUpload(file) { // 将文件对象存储到本地状态或其他持久化位置 this.localFiles.push(file.raw); // 返回 true 表示继续默认上传流程; false 可阻止上传 return true; } ``` 上述代码片段展示了如何拦截即将上传的文件并将它们临时存储在一个名为 `localFiles` 的数组中。这里假设 `file.raw` 是原始 File 对象,可以根据实际需求调整保存策略。 #### 自动触发保存动作而不依赖用户交互 如果希望更进一步自动化这一过程——即不等待用户点击提交按钮而是即时保存所选文件,则可以在 `on-change` 回调里立即采取行动: ```html <template> <!-- ... --> <el-upload :auto-upload="false" @change="handleChange"> <!-- ... --> </el-upload> </template> <script> export default { methods: { handleChange(file, fileList) { const isImage = file.raw.type.startsWith('image/'); if(isImage){ // 处理图片类型的特殊显示逻辑 console.log("Handling image preview..."); } // 不论何种类型都尝试保存下来 saveFileLocally(file.raw); function saveFileLocally(rawFile){ // 实现具体的保存机制,例如发送给服务器或存入浏览器缓存 console.log(`Saving ${rawFile.name} locally...`); // 这里的实现取决于应用的具体架构和技术栈 } }, }, }; </script> ``` 此段代码不仅实现了自动化的文件保存功能,还针对不同类型的文件提供了差异化的处理方式,特别是对于图像类文件能够提供更好的用户体验,如预览等功能[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值