springmvc上传多文件到指定服务器

    新来到一家公司,熟悉了基本的业务之后,就分配给我一个多文件上传的功能,由于本人之前的公司采用的架构是SSH,所以对springmvc还是比较陌生,也在网上找了许多关于多文件上传的资料,很显然,基本作用不大,经过长时间的探索,终于摸索了出来,下面我们就一起来看一下多文件是如何利用springmvc上传到指定服务器上的吧。

    1.搭建环境:不作说明。

    2.编写前台界面:

    html部分:

                    <p id="add">添加图片:

<input type="file" name="imgs" id="file1" />
        <input type="button" value="添加" id="addPhoto" />
        <!-- <span id="add"></span> -->

        </p>

    js部分:

     $("#addPhoto").click(function(){
        var html = $("<input type='file' name='imgs'>");
        var button = $("<input type='button' name='button' value='删除'>");
        $("#add").append(html).append(button);
        button.click(function()
        {
            html.remove();
            button.remove();
        });

    }); 

我这里的需求是图片上传,其实都一样,js主要是控制文件的个数。

    重点来了,请看后台代码:

    @RequestMapping("addshop.do")

public String addshop(@RequestParam("imgs") MultipartFile[] imgs) throws Exception {

            //fileUrl是图片的相对路径,这里我是用来存放到数据库,你们可以不用看,只需要看  FileUpload.uploadManyFile就可以了       

    String fileUrl = FileUpload.uploadManyFile(imgs);

    }

FileUpload.java

package com.store.liqiang.util;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;




import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;


public class FileUpload {
@SuppressWarnings("unlikely-arg-type")
public static String uploadManyFile(@RequestParam("imgs") MultipartFile[] imgs) throws Exception {
if(imgs!=null && !"".equals(imgs)) {
String imgUrl="";
for (MultipartFile img : imgs) {
            if (img.getSize() > 0) {
            String fileName=img.getOriginalFilename();
            //获取随机文件名
            String newFileName=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
Random random=new Random();
for(int i=0; i<3;i++){
newFileName=newFileName+random.nextInt(10);
}
//获取文件后缀名
String suffix=fileName.split("\\.")[1];
                String   realpath = ECPSUtils.readProp("upload_file_path")+"/upload/"+newFileName+"."+suffix;
                byte[] mfs =img.getBytes();
                Client  client=Client.create();
//指定要上传的具体地址,参数就是要上传的图片的绝对路劲
WebResource  wr = client.resource(realpath);
//文件的上传到的主机上。
wr.put(mfs);
imgUrl+=","+"/upload/"+fileName+"";
            }
}
if(!"".equals(imgUrl)) {
return imgUrl.substring(1);
}
}
return null;

}
}

好勒,这就是多文件上传到指定服务器,还请大家参考,如有好的建议或者不懂,欢迎下面留言。。。

    

猜你喜欢

转载自blog.csdn.net/qq_33220089/article/details/79509690