java对文件的操作

java实现文件上传到服务器

 来源:java实现文件上传到服务器_java_脚本之家 (jb51.net)

1、运行jar包,发送post请求

public static void main(String[] args) {

        //String filePath="C:/Users/706293/IT_onDuty.xls";
        String filePath=args[0];
        String unid=args[1];
       // String unid="155555";
        DataOutputStream out = null;
        final String newLine = "\r\n";
        final String prefix = "--";
        try {
            URL url = new URL("http://172.20.200.64:9000/excel9000/uploads");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            String BOUNDARY = "-------7da2e536604c8";
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            out = new DataOutputStream(conn.getOutputStream());

            // 添加参数file
            File file = new File(filePath);
            StringBuilder sb1 = new StringBuilder();
            sb1.append(prefix);
            sb1.append(BOUNDARY);
            sb1.append(newLine);
            sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine);
            sb1.append("Content-Type:application/octet-stream");
            sb1.append(newLine);
            sb1.append(newLine);
            out.write(sb1.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.write(newLine.getBytes());
            in.close();

            // 添加参数sysName
            StringBuilder sb = new StringBuilder();
            sb.append(prefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            sb.append("Content-Disposition: form-data;name=\"unid\"");
            sb.append(newLine);
            sb.append(newLine);
            sb.append(unid);
            out.write(sb.toString().getBytes());

             添加参数returnImage
            //StringBuilder sb2 = new StringBuilder();
            //sb2.append(newLine);
            //sb2.append(prefix);
            //sb2.append(BOUNDARY);
            //sb2.append(newLine);
            //sb2.append("Content-Disposition: form-data;name=\"returnImage\"");
            //sb2.append(newLine);
            //sb2.append(newLine);
            //sb2.append("false");
            //out.write(sb2.toString().getBytes());

            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
    }

2、服务器接收端,将文件上床服务器指定位置

package com.dayang.ExcelController;


import com.dayang.ExcelService.FileService;
import com.dayang.dubbo.CreateExcelConsumer;
import com.dayang.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class FileController {

    protected static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private CreateExcelConsumer createExcelConsumer;
    @Autowired
    FileService fileService;

    @PostMapping("/uploads")
    public String uploads(@RequestParam("file") MultipartFile file,@RequestParam("unid")String unid) throws IOException {
        //String unid="444444";
        String uploadPath = "";
        try{
            logger.info("==>uuid: " + unid);
            if (file == null) {
                logger.error("==>  没有上传文件。");
                return Result.error("没有上传文件。");
            }
            logger.info("==>文件名: " + file.getOriginalFilename());
             uploadPath = fileService.handlerMultipartFile(file,unid);
            //return Result.success("文件上传完成。", newFileName);
            //uploadPath = createExcelConsumer.uploadExcel(file,unid);
            logger.info("==>文件路径: " + uploadPath);
        }
        catch (Exception e){

        }

        return uploadPath;

    }
    @RequestMapping("/test")
    public  String  test(){
        System.out.println("test测试成功。");
        logger.info("==>  测试成功。");
        return  "test";
    }

}

3、service

package com.dayang.ExcelService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Service
public class FileService {

    protected static final Logger logger= LoggerFactory.getLogger(FileService.class);

    private String directoryPath = "C:\\Temp";

    public FileService() {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    public String handlerMultipartFile(MultipartFile multipartFile ,String unid) {
        String fileOldName = multipartFile.getOriginalFilename();
        int beginIndex = fileOldName.lastIndexOf(".");
       String suffix = fileOldName.substring(beginIndex);
        String newFileName =  unid+ suffix;
        File upFile = new File(directoryPath + "/" + newFileName);
        OutputStream outputStream = null;
        try {
            byte[] fileByte = multipartFile.getBytes();
            outputStream = new FileOutputStream(upFile);
            outputStream.write(fileByte);
            logger.info("<==  文件写出完成: " + newFileName);
            return newFileName;
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        return directoryPath + "/" + newFileName;
    }

}

4、Result

package com.dayang.util;

import com.alibaba.fastjson.JSONObject;

public class Result {

    public static String success(String msg, Object result) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 1);
        jsonObject.put("message", msg);
        jsonObject.put("result", result);
        return jsonObject.toJSONString();
    }

    public static String error(String msg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", -1);
        jsonObject.put("message", msg);
        return jsonObject.toJSONString();
    }

}

Java根据url下载文件到本地

来源:Java根据url下载文件到本地_不会编码的灯泡的博客-CSDN博客

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
 
//---------------------------------------------------------
 
public static String download(String urlString) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            String filename = System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg";
            File file = new File(filename);
            os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
 
            return filename;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕,关闭所有链接
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //从微信下载图片时如果没有id对应的图片则下载一个空图片,不会存在返回为null的情况
        return null;
    }

有下载肯定要有删除,也以删除图片为例,可根据需要自行调整

    public static Boolean deleteImage() {
        File file = new File(System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg");
        return !file.exists() || file.delete();
    }
 
//------------------业务中我是这样用的删除----------------------------
 
    private Boolean deleteImage() {
        int i = 0;
        boolean flag = deleteImage();
        while (i >= 3 || !flag) {
            i++;
            flag = deleteImage();
        }
        return flag;
    }

java将网络路径图片上传至服务器

来源:java将网络路径图片上传至服务器_sun_Beauty的博客-CSDN博客

需求:将将微信头像(例:https://thirdwx.qlogo.cn/mmopen/vi_32/Q0jsdfsdfdsf/132)上传至服务器

思路:
1.先将路径通过URL转换成文件流(InputStream)

/**
 * 通过网络地址获取文件InputStream
 * @param path 地址
 * @return
 */
private static InputStream returnBitMap(String path) {
    URL url = null;
    InputStream is = null;
    try {
        url = new URL(path);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
        conn.setDoInput(true);
        conn.connect();
        is = conn.getInputStream();    //得到网络返回的输入流

    } catch (IOException e) {
        e.printStackTrace();
    }
    return is;
}

2.再把文件流(InputStream)转换成MultipartFile上传

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>RELEASE</version>
</dependency>
MultipartFile multipartFile = new MockMultipartFile("temp.jpg","temp.jpg","", inputStream);
MultipartFile multipartFile = new MockMultipartFile("temp.jpg","temp.jpg",
        ContentType.APPLICATION_OCTET_STREAM.toString(), returnBitMap(fileName));

3.向一个带参的地址上传图片

private final static String BOUNDARY = UUID.randomUUID().toString()
        .toLowerCase().replaceAll("-", "");// 边界标识
private final static String PREFIX = "--";// 必须存在
private final static String LINE_END = "\r\n";

/**
 *  POST 向一个带参的地址上传图片
 *  @Description:
 *  @param requestUrl 请求url
 *  @param fileName 请求上传的文件
 *  @return
 *  @throws Exception
 */
public static String sendRequest(String requestUrl,String fileName) throws Exception{
    HttpURLConnection conn = null;
    InputStream input = null;
    OutputStream os = null;
    BufferedReader br = null;
    StringBuffer buffer = null;
    try {
        URL url = new URL(requestUrl);
        conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(1000 * 10);
        conn.setReadTimeout(1000 * 10);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Connection", "keep-alive");
        //设置头部参数
        //conn.setRequestProperty("ticket", ticket);
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        conn.connect();

        // 往服务器端写内容 也就是发起http请求需要带的参数
        os = new DataOutputStream(conn.getOutputStream());


        Map<String,MultipartFile> requestFile = new HashMap<String,MultipartFile>();
        MultipartFile multipartFile = new MockMultipartFile("temp.jpg","temp.jpg",
                ContentType.APPLICATION_OCTET_STREAM.toString(), returnBitMap(fileName));
        //带参
        requestFile.put("file",multipartFile);

        // 请求上传文件部分
        writeFile(requestFile, os);
        // 请求结束标志
        String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
        os.write(endTarget.getBytes());
        os.flush();

        // 读取服务器端返回的内容
        System.out.println("======================响应体=========================");
        System.out.println("ResponseCode:" + conn.getResponseCode()
                + ",ResponseMessage:" + conn.getResponseMessage());
        if(conn.getResponseCode()==200){
            input = conn.getInputStream();
        }else{
            input = conn.getErrorStream();
        }

        br = new BufferedReader(new InputStreamReader( input, "UTF-8"));
        buffer = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        try {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            if (os != null) {
                os.close();
                os = null;
            }
            if (br != null) {
                br.close();
                br = null;
            }
        } catch (IOException ex) {
            throw new Exception(ex);
        }
    }
}


/**
 * 对post上传的文件进行编码处理并写入数据流中
 * @throws IOException
 * */
private static void writeFile(Map<String, MultipartFile> requestFile,
                              OutputStream os) throws Exception {
    InputStream is = null;
    try{
        String msg = "请求上传文件部分:\n";
        if (requestFile == null || requestFile.isEmpty()) {
            msg += "空";
        } else {
            StringBuilder requestParams = new StringBuilder();
            Set<Map.Entry<String, MultipartFile>> set = requestFile.entrySet();
            Iterator<Map.Entry<String, MultipartFile>> it = set.iterator();
            while (it.hasNext()) {
                Map.Entry<String, MultipartFile> entry = it.next();
                if(entry.getValue() == null){//剔除value为空的键值对
                    continue;
                }
                requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
                requestParams.append("Content-Disposition: form-data; name=\"")
                        .append(entry.getKey()).append("\"; filename=\"")
                        .append(entry.getValue().getName()).append("\"")
                        .append(LINE_END);
                requestParams.append("Content-Type:")
                        .append(entry.getValue().getContentType())
                        .append(LINE_END);
                requestParams.append("Content-Transfer-Encoding: 8bit").append(
                        LINE_END);
                requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容

                os.write(requestParams.toString().getBytes());
                os.write(entry.getValue().getBytes());

                os.write(LINE_END.getBytes());
                os.flush();

                msg += requestParams.toString();
            }
        }
        //System.out.println(msg);
    }catch(Exception e){
        throw new Exception(e);
    }finally{
        try{
            if(is!=null){
                is.close();
            }
        }catch(Exception e){
            throw new Exception(e);
        }
    }
}

java上传本地照片到服务器

来源:java上传本地照片到服务器_刘刘刘子的博客-CSDN博客

		<!--//ftp上传-->
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>3.3</version>
		</dependency>

引入工具类 FtpUtil

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * ftp上传下载工具类
 */
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;
    }
  
}

代码调用

 public static void main(String[] args) {
        try {
        	
           InputStream is = new FileInputStream("D:/pic/1.jpg");
           //IP   端口   账号   密码  根路径  保存目录   保存文件名   图片
			boolean result = FtpUtil.uploadFile(
							"192.168.1.166", 21, "www", "123456", "", "bbb", "2.jpg", is);
			if (result) {
				System.out.println("上传成功");
			} else {
				System.out.println("上传失败");
			}
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

Java SpringBoot 上传图片到服务器

来源:Java SpringBoot 上传图片到服务器,完美可用_普通网友的博客-CSDN博客

上传文件的工具类

import java.io.File;
import java.io.FileOutputStream;

/**
 * @Author: Manitozhang
 * @Data: 2019/1/9 16:51
 * @Email: manitozhang@foxmail.com
 *
 * 文件工具类
 */
public class FileUtil {

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}
    @Resource
    HttpServletRequest request;

    //处理文件上传
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //设置文件上传路径
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            return "上传成功";
        } catch (Exception e) {
            return "上传失败";
        }
    }

因为我们的路径是上传到SpringBoot自带的Tomcat服务器中,所以在项目中看不到,不过可以直接获取到。上传位置可以修改。

声明:这个方法只要Tomcat重启之后之前上传的图片就会丢失

**Java通过图片URL把图片上传到本地服务器

来源:Java通过图片URL把图片上传到本地服务器_Jon Young的博客-CSDN博客

在工作中通常有这么个需求:跟第三方对接数据,第三方给的图片数据只有一个url链接,这就导致我们访问图片资源要一直请求第三方的资源。万一第三方做了限制或者删除,就导致我们这边的图片资源访问不到了。这就需要我们把第三方的图片url实时转存到我们的服务器上,真正的实现资源自由。

其实实现逻辑很简单:
①首先通过URL从HTTP响应获取资源
②然后把资源转成文件流
③最后以文件流的形式上传图片到服务器

@RestController
@RequestMapping("/upload")
public class TestController {

    @GetMapping("/testUpload")
    public String testUpload(){
        try {
            //网络图片资源的url(可以把这个放参数中动态获取)
            String picUrl = "http://img1.gtimg.com/chinanba/pics/hv1/220/29/2326/151255765.jpg";
            //获取原文件名
            String fileName = picUrl.substring(picUrl.lastIndexOf("/")+1);
            //创建URL对象,参数传递一个String类型的URL解析地址
            URL url = new URL(picUrl);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            //从HTTP响应消息获取状态码
            int code = huc.getResponseCode();
            if (code == 200) {
                //获取输入流
                InputStream ips = huc.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((len = ips.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.close();
                return uploadFileByBytes(bos.toByteArray(),fileName);
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }

    private String uploadFileByBytes(byte[] bytes, String fileName) throws Exception {
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        String realPath = System.getProperty("user.dir") + File.separator + "upload" + File.separator;
        //文件路径
        String url = realPath + fileName;
        //判断文件路径是否存在,如果没有则新建文件夹
        File files = new File(realPath);
        if(!files.exists()){
            files.mkdirs();
        }
        //把文件写入到指定路径下
        try(OutputStream out = new BufferedOutputStream(new FileOutputStream(url, false))){
            out.write(bytes);
        }
        return url;
    }
}

java 文件保存到本地

来源:java 文件保存到本地 (shuzhiduo.com)

package com.ebways.web.upload.controller;
 
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import com.ebways.web.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ebways.web.upload.url.UploadURL;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@Controller
@RequestMapping(value = UploadURL.MODE_NAME)
public class UploadController extends BaseController {
 
    @RequestMapping(value = UploadURL.IMAGE_UPLOAD)
    @ResponseBody
    public String uploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, Exception {
        // 参数列表
        Map<String, Object> map = new HashMap<>();
        map.put("file", file);
        savePic(file.getInputStream(), file.getOriginalFilename());
 
        //请求接口
        String apiReturnStr = "";//apiHttpRequest(map, API_HOST_URL + "/image/upload");
 
        return apiReturnStr;
    }
 
    private void savePic(InputStream inputStream, String fileName) {
 
        OutputStream os = null;
        try {
            String path = "D:\\testFile\\";
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
 
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
 
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕,关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * <p class="detail">
     * 功能:公共Action
     * </p>
     *
     * @date 2016年9月8日
     * @author wangsheng
     */
    private String allowSuffix = "jpg,png,gif,jpeg";//允许文件格式
    private long allowSize = 2L;//允许文件大小
    private String fileName;
    private String[] fileNames;
 
    public String getAllowSuffix() {
        return allowSuffix;
    }
 
    public void setAllowSuffix(String allowSuffix) {
        this.allowSuffix = allowSuffix;
    }
 
    public long getAllowSize() {
        return allowSize * 1024 * 1024;
    }
 
    public void setAllowSize(long allowSize) {
        this.allowSize = allowSize;
    }
 
    public String getFileName() {
        return fileName;
    }
 
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
 
    public String[] getFileNames() {
        return fileNames;
    }
 
    public void setFileNames(String[] fileNames) {
        this.fileNames = fileNames;
    }
 
    /**
     * <p class="detail">
     * 功能:重新命名文件
     * </p>
     *
     * @return
     * @author wangsheng
     * @date 2016年9月8日
     */
    private String getFileNameNew() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }
 
    /**
     * <p class="detail">
     * 功能:文件上传
     * </p>
     *
     * @param files
     * @param destDir
     * @throws Exception
     * @author wangsheng
     * @date 2014年9月25日
     */
    public void uploads(MultipartFile[] files, String destDir, HttpServletRequest request) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        try {
            fileNames = new String[files.length];
            int index = 0;
            for (MultipartFile file : files) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                int length = getAllowSuffix().indexOf(suffix);
                if (length == -1) {
                    throw new Exception("请上传允许格式的文件");
                }
                if (file.getSize() > getAllowSize()) {
                    throw new Exception("您上传的文件大小已经超出范围");
                }
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File destFile = new File(realPath + destDir);
                if (!destFile.exists()) {
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew() + "." + suffix;//
                File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);
                file.transferTo(f);
                f.createNewFile();
                fileNames[index++] = basePath + destDir + fileNameNew;
            }
        } catch (Exception e) {
            throw e;
        }
    }
 
    /**
     * <p class="detail">
     * 功能:文件上传
     * </p>
     *
     * @param file
     * @param destDir
     * @throws Exception
     * @author wangsheng
     * @date 2016年9月8日
     */
    public void upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            int length = getAllowSuffix().indexOf(suffix);
            if (length == -1) {
                throw new Exception("请上传允许格式的文件");
            }
            if (file.getSize() > getAllowSize()) {
                throw new Exception("您上传的文件大小已经超出范围");
            }
 
            String realPath = request.getSession().getServletContext().getRealPath("/");
            File destFile = new File(realPath + destDir);
            if (!destFile.exists()) {
                destFile.mkdirs();
            }
            String fileNameNew = getFileNameNew() + "." + suffix;
            File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);
            file.transferTo(f);
            f.createNewFile();
            fileName = basePath + destDir + fileNameNew;
        } catch (Exception e) {
            throw e;
        }
    }
 
}

Java后台将文件上传至远程服务器

来源:【Java】后台将文件上传至远程服务器 - 朝雾轻寒 - 博客园 (cnblogs.com)

问题:由于系统在局域网(能访问外网)内,但外网无法请求局域网内服务器文件和进行处理文件。

解决:建立文件服务器,用于存储文件及外网调用。

客户端(文件上传):

package cn.hkwl.lm.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadToServer {
     private static final Logger log = LoggerFactory.getLogger(UploadToServer.class);


     public static String postFile(String url,Map<String, Object> param, File file) throws ClientProtocolException, IOException {
            String res = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(getMutipartEntry(param,file));
            CloseableHttpResponse response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                res = EntityUtils.toString(entity, "UTF-8");
                response.close();
            } else {
                res = EntityUtils.toString(entity, "UTF-8");
                response.close();
                throw new IllegalArgumentException(res);
            }
            return res;
        }
     
     private static MultipartEntity getMutipartEntry(Map<String, Object> param, File file) throws UnsupportedEncodingException {
            if (file == null) {
                throw new IllegalArgumentException("文件不能为空");
            }
            FileBody fileBody = new FileBody(file);
            FormBodyPart filePart = new FormBodyPart("file", fileBody);
            MultipartEntity multipartEntity = new MultipartEntity();
            multipartEntity.addPart(filePart);

            Iterator<String> iterator = param.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                FormBodyPart field = new FormBodyPart(key, new StringBody((String) param.get(key)));
                multipartEntity.addPart(field);

            }
            return multipartEntity;
        }

}

服务器端(文件接收):

package cn.hkwl.office.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.jasper.tagplugins.jstl.core.Out;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.zy.action.BaseAction;

@Controller
@RequestMapping("/file")
public class FileAction extends BaseAction {
    /**
     * 
     */
    private static final long serialVersionUID = -5865227624891447594L;
    
    @RequestMapping("/receive")
    public @ResponseBody void receive(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        JSONObject json=new JSONObject();
        // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator<String> iter = multiRequest.getFileNames();

            // 定义绝对路径
            String localPath = getRealPath("/upload/lm");
            File path = new File(localPath);
            // 文件夹不存在 则创建文件夹
            if (!path.exists()) {
                path.mkdir();
            }

            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next()
                        .toString());
                if (file != null) {
                    String filepath = localPath +File.separator+ file.getOriginalFilename();
                    // 上传
                    file.transferTo(new File(filepath));
                    // 文件数据存储起来
                    json.put("success", true);
                    json.put("httpUrl", "http://serverhostip:9080/lmoffice/upload/lm/"+file.getOriginalFilename());
                }
            }

        }else{
            json.put("success", false);
        }
        outJson(json);
    }

}

应用使用:

private String getHttpUrl(String savePath) throws ClientProtocolException, IOException{
        File file=new File(getRealPath(savePath));
        System.out.println(file.exists());
        Map<String,Object> param=new HashMap<String, Object>();
        String res=UploadToServer.postFile("http://serverhostip:9080/lmoffice/file/receive",param,file);
        JSONObject result=JSONObject.fromObject(res);
        if(result.getBoolean("success")){
            file.delete();//删除本地文件
            return result.getString("httpUrl");
        }
        return "";
        
    }

/***
     * 管线迁移公告
     * 
     * @param landId
     */
    @RequestMapping("/gxqygg.do")
    public @ResponseBody
    void createGXQYGG(Long landId) {
        JSONObject json = new JSONObject();
        Land land = landService.getLandInfo(landId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("land", land);
        Calendar calendar = Calendar.getInstance();// 取当前日期。
        map.put("year", calendar.get(Calendar.YEAR) + "");
        map.put("month",
                (calendar.get(Calendar.MONTH) + 1 > 12 ? calendar
                        .get(Calendar.MONTH) - 11 : calendar
                        .get(Calendar.MONTH) + 1)
                        + "");
        map.put("day", calendar.get(Calendar.DATE) + "");
        try {
            //通过freemark动态生成word文件
            String savePath = WordUtils
                    .exportMillCertificateWordReturnSavePath(getRequest(),
                            getResponse(), map, "管线迁移公告", "gxqygg.ftl",
                            "word/gxqygg");
            
            
            json.put("success", true);
            json.put("savePath",getHttpUrl(savePath));//获取上传后网络路径
            outJson(json);
        } catch (Exception e) {
            e.printStackTrace();
            json.put("success", false);
            json.put("error", e.toString());
            outJson(json);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值