文件上传

Posted melovemingming

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件上传相关的知识,希望对你有一定的参考价值。

代码如下

package com.ming;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class uploadFile extends ActionSupport {
    private File myFile;
    private String myFileContentType;
    private String myFileFileName;
    private String destPath;

    @Override
    public String execute()
    {
        Logger logger = LogManager.getLogger();
        // 获取到Action执行的上下文
        destPath = ServletActionContext.getServletContext().getRealPath("/");
        // 拼接目录
        destPath = destPath + "upload/";
        // 新建文件
        File tmpFile = new File(destPath, new Date().toString() + this.myFileFileName);
        try{
            FileUtils.copyFile(myFile, tmpFile);
        }catch (Exception e){
            logger.info(e);
        }
        logger.info(myFileContentType);
        return SUCCESS;
    }
    public File getMyFile() {
        return myFile;
    }
    public void setMyFile(File myFile) {
        this.myFile = myFile;
    }
    public String getMyFileContentType() {
        return myFileContentType;
    }
    public void setMyFileContentType(String myFileContentType) {
        this.myFileContentType = myFileContentType;
    }
    public String getMyFileFileName() {
        return myFileFileName;
    }
    public void setMyFileFileName(String myFileFileName) {
        this.myFileFileName = myFileFileName;
    }
}

核心思路 是 获取到当前action上下文件,接着获取容器上下文,在进行绝对路径拼接,拼接完成以后,新建file文件,然后,文件内容写入即可.

配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <!-- 定义调试 -->
    <constant name="struts.devMode" value="true" />
    <constant name="struts.multipart.maxSize" value="1000000" />
    <package name="helloworld" extends="struts-default">
        <action name="upload" class="com.ming.uploadFile">
            <interceptor-ref name="defaultStack"/>
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">image/jpeg,image/gif</param>
            </interceptor-ref>
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

技术图片

以上是关于文件上传的主要内容,如果未能解决你的问题,请参考以下文章

将存储在内存中的文件上传到s3

JS创建文件并上传服务器

ajaxFileUpload上传带参数文件及JS验证文件大小

android的自带的httpClient 怎么上传文件

大文件上传下载实现思路,分片断点续传代码实现,以及webUpload组件

如何通过 HttpWebRequest 上传文件?