java上传文件夹到服务器,Java实现文件上传
本文实例为大家分享了爪哇岛实现文件上传到服务器的具体代码,供大家参考,具体内容如下
1、运行冲突包,发送邮政请求
public static void main(String[]args){//String文件路径= c :/Users/706293/IT _ on duty。xls ;字符串文件路径=args[0];string unid=args[1];//String unid= 155555 ;DataOutputStream out=null最后一个字符串newLine= r n最终字符串前缀=-;尝试{ URL URL=新URL( http://172。20 .200 .64:9000/excel 9000/uploads’);http URL connection conn=(http URL connection)URL。打开连接();字符串边界=-7da 2e 536604 c8 ;conn . setrequestmethod( POST );//发送邮政请求必须设置如下两行conn . setdoooutput(true);conn . setdoinput(true);conn . setusecaches(false);conn.setRequestProperty(连接,保持活动);conn . setrequestproperty( Charsert , UTF-8 );conn . setrequestproperty( Content-Type , multipart/form-data;边界=边界);out=新数据输出流(conn . get output stream());//添加参数文件文件=新文件(文件路径);StringBuilder sb1=new StringBuilder();sb1.append(前缀);sb1.append(边界);sb1.append(换行符);sb1。append( Content-disposition :表单数据;name= file filename= file。getname() newLine);sb1。append(内容类型:应用程序/八位字节流);sb1.append(换行符);sb1.append(换行符);out.write(sb1.toString().getBytes());数据输入流in=新数据输入流(新文件输入流(文件));字节[]缓冲区输出=新字节[1024];int bytes=0;while ((bytes=in.read(bufferOut))!=-1) { out.write(bufferOut,0,bytes);}出。写(换行符。getbytes());英寸close();//添加参数sysName StringBuilder sb=new StringBuilder();某人追加(前缀);某人(somebody的简写)追加(边界);某人追加(换行符);某人(somebody的简写)附加(内容处置:表单数据;name= unid );某人追加(换行符);某人追加(换行符);某人(somebody的简写)追加(unid);牛津大学
t.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 = ("rn--" + BOUNDARY + "--rn").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;@RestControllerpublic 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;@Servicepublic 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(); }}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。