首页 > 编程语言 >java实现文件上传到服务器

java实现文件上传到服务器

时间:2023-10-23 17:44:25浏览次数:27  
标签:java String newLine new 传到 import 服务器 append out

本文实例为大家分享了java实现文件上传到服务器的具体代码,供大家参考,具体内容如下

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();
    }

}

 

参考文章:http://blog.ncmem.com/wordpress/2023/10/23/java%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%88%b0%e6%9c%8d%e5%8a%a1%e5%99%a8/

欢迎入群一起讨论

 

 

标签:java,String,newLine,new,传到,import,服务器,append,out
From: https://www.cnblogs.com/songsu/p/17783068.html

相关文章

  • 【文心一言】百度千帆 Python 和 JavaScript 调用上下文 API
    接口为:百度ERNIE-Bot-4(邀测)控制台直达链接JavascriptconstAK="urAK"constSK="urSK"constaxios=require("axios").default;letaccess_token="urtoken"varurl='https://aip.baidubce.com/rpc/2.0/ai_custom/v1/w......
  • nacos启动脚本去除多余的javac
    github上面一个阿里巴巴开源的服务叫nacos,用途在这里不多说了,主要是在启动时他会寻找javac,但是很多服务器可能没有,所以我小小的修改了一下他的startup.sh然后给他打成了rpm包,也不知道网站可不可以直接把包传上来,这里是github的地址,乱放在一个仓库里面的:https://github.com/linux......
  • 跨境电商服务器购买时需要考虑一些因素
    跨境电商服务器购买时需要考虑一些因素就搭建跨境电商的网站来说其实有很多选项可以选择,因此在跨境电商服务器购买时需要考虑一些因素。如何选择合适的服务器确定服务器的硬件配置、网络环境、IP地址是否适合您的业务使用服务器机房是否能够提供相应的解决方案来满足跨境电商网站......
  • sqlserver 服务器主体 无法在当前安全上下文下访问数据库
    SELECTname,database_id,is_trustworthy_onFROMsys.databasesALTERDATABASEbole_dataSETTRUSTWORTHYONALTERAUTHORIZATIONONDATABASE::bole_dataTObole 今天使用sqlserver,发现了一个问题,就是使用insertinto数据库名.dbo.表名(字段)values(值)这样语句的......
  • java8 map过滤 map转字符串
    Map<String,Long>map=newHashMap<>();map.put("aaa",1L);map.put("bbb",2L);map.put("ccc",1L);Map<String,Long>map2=map.entrySet().stream().filter(e->e.getValue().intValue()>1).collect(Coll......
  • Java基础 字节输入流 读取数据 的两个方法API
    public int read()  →  一次读取一个字节数据public int read(byte[] buffer)  →  一次读取一个字节数组的数据,每次读取都会尽可能把数组装满我们创建的数组的长度尽量是1024的整数倍,例如1024*1024*5的长度 ......
  • java上传文件到服务器指定目录
    问题描述:如何在Java中实现文件上传功能,并将上传的文件保存到服务器的指定目录?解答:在Java中,可以使用一些库和框架来实现文件上传功能,其中最常用的是使用ApacheCommonsFileUpload库。下面将详细介绍如何使用该库来实现文件上传并将文件保存到服务器指定目录的过程。步骤一:导入......
  • Java基础 文件拷贝的基本代码
    FileInputStreamfis=newFileInputStream("E:\\Java基础资料\\a.txt");FileOutputStreamfos=newFileOutputStream("E:\\Java基础资料\\b.txt");while(true){intb=fis.read();if(b==-1)break;fos.write(b);}fos.close......
  • Java基础 字节输入流的循环读取
    FileInputStreamfis=newFileInputStream("E:\\Java基础资料\\a.txt");/*intb;while((b=fis.read())!=-1){System.out.print((char)b);}*/while(true){intb=fis.read();if(b==-1)break;System.out.print((char)b);}fis.clo......
  • Java基础 FileInputStream 字节输入流的细节
    1.创建字节输入流对象:FileInputStreamfis=newFileInputStream("E:\\Java基础资料\\a.txt");细节:如果文件不存在,就直接报错 2.读取数据(read方法负责读取数据,会一个一个地读,如果读不到了,就会返回-1)细节①:一次读取一个字节,读出来的是数据在ASCII码表上对应的数字细节......