java上传文件到服务器(淘淘商城源码)

先介绍一下项目,本项目采用的是spring mvc +spring +mybatis ,用maven 进行项目管理。看一下项目结构 。

        

        如果单独做测试的话不用这么费劲,写一个简单的测试类就ok了!而在这个项目中,parent是所有项目的父包,其他的项目都把该项目做为父项目。common中放入的是一些公用的工具类,pojo对象等,pojo和mapper项目是mybatis逆向生成的项目。而service 是处理业务逻辑的项目,web 是展示层的项目。介绍完了,直接看我们要求的代码。

        上传文件需要的工具类。代码如下所示,这个东西一般不用自己再写了,网上有很多,直接找一个用就可以了,但是要弄懂它的意思。

public class FtpUtil {
 
    /** 
     * Description: 向FTP服务器上传文件 
     * @param host FTP服务器hostname 
     * @param port FTP服务器端口 
     * @param username FTP登录账号 
     * @param password FTP登录密码 
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名 
     * @param input 输入流 
     * @return 成功返回true,否则返回false 
     */  
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
            String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
    
    /** 
     * Description: 从FTP服务器下载文件 
     * @param host FTP服务器hostname 
     * @param port FTP服务器端口 
     * @param username FTP登录账号 
     * @param password FTP登录密码 
     * @param remotePath FTP服务器上的相对路径 
     * @param fileName 要下载的文件名 
     * @param localPath 下载后保存到本地的路径 
     * @return 
     */  
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
            String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());
 
                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
 
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}

我们的pojo项目和mapper项目,不需要写代码,在service层要做一些处理,判断是否上传成功。会看到如何代码有很多的获取值的,因为我们不能见ftp服务器的一些信息都写死到代理吗,我们要把它放入配置文件中,可以是xml文件,或者properties等,这里采用的是properties文件形式。Service 项目是jar 类型的,最后要打成jar包,放入到web项目中,所以所有的配置文件信息应该都放入web项目中。

          

         我们ftp配置信息在resource.properties文件中,如下所示,在写这个配置文件的时候千万要注意所有的值前后不要空格,所有的值前后不要空格,所有的值前后不要空格,重要的事情讲三遍,我就是因为一个空格弄了整整半天。

#ftp相关配置
FTP_ADDRESS=192.168.xx.xxx
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=123456
FTP_BASEPATH=/home/ftpuser/www/images
#图片服务器相关配置i
IMAGE_BASE_URL=http://192.168.xx.xxx/www/images

配置完resource.properties以后,要确保在项目启动的时候一定要加载这个文件,在配置文件中加上这句话。<!-- 加载配置文件 -->

         <context:property-placeholderlocation="classpath:resource/*.properties" /> 这样就可以保证配置文件会被加载了。

         然后我们在service中写自己的业务逻辑,

@Service
public class PictureServiceImpl implements PictureService {
 
    //获取ip地址
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    //端口号
    @Value("${FTP_PORT}")
    private String FTP_PORT;
    //用户名
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    //密码
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    //基本路径
    @Value("${FTP_BASEPATH}")
    private String FTP_BASEPATH;
    //下载地址地基础url
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;
 
    @Override
    public Map uploadPicture(MultipartFile uploadFile) {
        Map resultmMap = new HashMap<>();
 
        try {
            // 生成一个文件名
            // 获取旧的名字
            String oldName = uploadFile.getOriginalFilename();
            String newName = IDUtils.genImageName();
            //新名字
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //上传的路径
            String imagePath = new DateTime().toString("/yyyy/mm/dd");
            //端口号
            int port = Integer.parseInt(FTP_PORT);
            System.out.println(FTP_BASEPATH);
            //调用方法,上传文件
            boolean result = FtpUtil.uploadFile(FTP_ADDRESS, port,
                    FTP_USERNAME, FTP_PASSWORD, FTP_BASEPATH, imagePath,
                    newName, uploadFile.getInputStream());
            //判断是否上传成功
            if (!result) {
                resultmMap.put("error", 1);
                resultmMap.put("message", "上传失败");
                return resultmMap;
            }
            resultmMap.put("error", 0);
            resultmMap.put("url", IMAGE_BASE_URL + imagePath + newName);
            return resultmMap;
 
        } catch (IOException e) {
            resultmMap.put("error", 1);
            resultmMap.put("message", "上传发生异常");
            return resultmMap;
        }
    }
}

   Controler中服务请求的转发工作。代码如下。

@Controller
public class PictureController {
    
    @Autowired
    private PictureService pictureService;
    
    @RequestMapping("/pic/upload")
    @ResponseBody
    public Map pictureUpload(MultipartFile uploadFile){
        Map result = pictureService.uploadPicture(uploadFile);
        return result;
    }
}

在jsp 页面中我们用

<span style="font-size:18px;">    <a href="javascript:void(0)" class="easyui-linkbuttonpicFileUpload">上传图片</a>
   <inputtype="hidden" name="image"/></span>

而调用到js代码如下所示

 // 初始化图片上传组件
    initPicUpload : function(data){
        $(".picFileUpload").each(function(i,e){
            var _ele = $(e);
            _ele.siblings("div.pics").remove();
            _ele.after('\
                <div class="pics">\
                    <ul></ul>\
                </div>');
            // 回显图片
            if(data && data.pics){
                var imgs = data.pics.split(",");
                for(var i in imgs){
                    if($.trim(imgs[i]).length > 0){
                        _ele.siblings(".pics").find("ul").append("<li><a href='"+imgs[i]+"' target='_blank'><img src='"+imgs[i]+"' width='80' height='50' /></a></li>");
                    }
                }
            }
            //给“上传图片按钮”绑定click事件
            $(e).click(function(){
                var form = $(this).parentsUntil("form").parent("form");
                //打开图片上传窗口
                KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){
                    var editor = this;
                    editor.plugin.multiImageDialog({
                        clickFn : function(urlList) {
                            var imgArray = [];
                            KindEditor.each(urlList, function(i, data) {
                                imgArray.push(data.url);
                                form.find(".pics ul").append("<li><a href='"+data.url+"' target='_blank'><img src='"+data.url+"' width='80' height='50' /></a></li>");
                            });
                            form.find("[name=image]").val(imgArray.join(","));
                            editor.hideDialog();
                        }
                    });
                });
            });
        });
    },

这些代码都写完以后,我们测试会发现依然有问题,Expected MultipartHttpServletRequest: is a MultipartResolverconfigured 这个错误是因为我们没有配置解析文件的jar。所以我们还要在springmvc的配置文件中加上如下配置。这样我们应该就没问题了!

<span style="font-size:18px;"><!-- 上传文件拦截,设置最大上传文件大小10M=10*1024*1024(B)=10485760 bytes -->
   <bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="maxUploadSize"value="10485760" />
   </bean></span>

OK!!!!!

posted @ 2018-11-27 13:57  烟雨观春柳  阅读(187)  评论(0)    收藏  举报