删除上传到服务器端的文件,MultipartFile 上传、删除文件到静态资源服务器

第一步 首先是要文件传输,类似于文件传输的代码网上一大把

/**

* 上传文件到静态资源服务器

* @param fileType 文件类型(1:图片;2:文件;3:语音)

* @param is 图片文件流

* @param filename 文件名

* @param fileDir 文件目录(模块名/功能名;如:"usercenter/user")

* @param isResize 是否压缩图片

* @param subFileName 子文件名

* @return

*/

@SuppressWarnings("unchecked")

public static String uploadFileToServer(String fileType, InputStream is, String filename, String fileDir,

boolean isResize, String subFileName) {

String res = "";

HttpURLConnection conn = null;

// boundary就是request头和上传文件内容的分隔符

String BOUNDARY = "--------------------------------";

try {

String urlType = "";

if ("1".equals(fileType)) {

urlType = UPLOAD_IMAGE;

} else if ("2".equals(fileType)) {

urlType = UPLOAD_FILE;

} else if ("3".equals(fileType)) {

urlType = UPLOAD_VOICE;

}

URL url = new URL(getServerUploadUrl() + urlType);

conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(30000);

conn.setReadTimeout(30000);

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");

conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

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

// 传参数

StringBuffer sb = new StringBuffer();

sb.append("--").append(BOUNDARY).append("\r\n");

sb.append("Content-Disposition: form-data; name=\"fileDir\"").append("\r\n").append("\r\n");

sb.append(fileDir).append("\r\n");

out.write(sb.toString().getBytes());

sb = new StringBuffer();

sb.append("--").append(BOUNDARY).append("\r\n");

sb.append("Content-Disposition: form-data; name=\"isResize\"").append("\r\n").append("\r\n");

sb.append(isResize).append("\r\n");

out.write(sb.toString().getBytes());

if (StrUtil.isNotEmpty(subFileName)) {

sb = new StringBuffer();

sb.append("--").append(BOUNDARY).append("\r\n");

sb.append("Content-Disposition: form-data; name=\"subFileName\"").append("\r\n").append("\r\n");

sb.append(subFileName);

out.write(sb.toString().getBytes());

}

// 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream

String contentType = null;

// contentType非空采用filename匹配默认的图片类型

if (filename.endsWith(".png")) {

contentType = "image/png";

} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {

contentType = "image/jpeg";

} else if (filename.endsWith(".gif")) {

contentType = "image/gif";

} else if (filename.endsWith(".ico")) {

contentType = "image/image/x-icon";

}

if (contentType == null || "".equals(contentType)) {

contentType = "application/octet-stream";

}

sb = new StringBuffer();

sb.append("\r\n").append("--").append(BOUNDARY).append("\r\n");

sb.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + filename + "\"\r\n");

sb.append("Content-Type:" + contentType + "\r\n\r\n");

out.write(sb.toString().getBytes());

DataInputStream in = new DataInputStream(is);

int bytes = 0;

byte[] bufferOut = new byte[1024];

while ((bytes = in.read(bufferOut)) != -1) {

out.write(bufferOut, 0, bytes);

}

in.close();

byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();

out.write(endData);

out.flush();

out.close();

// 读取返回数据

StringBuffer strBuf = new StringBuffer();

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line = null;

while ((line = reader.readLine()) != null) {

strBuf.append(line).append("\n");

}

res = strBuf.toString();

reader.close();

reader = null;

ObjectMapper mapper = new ObjectMapper();

Map map = mapper.readValue(res, Map.class);

if (MapUtil.getInt(map, "result") == 1) {

return map.get("content").toString();

} else {

StaticLog.error("上传文件失败:{}", map.get("errmsg"));

return null;

}

} catch (Exception e) {

StaticLog.error(e, "上传文件失败");

return null;

} finally {

if (conn != null) {

conn.disconnect();

conn = null;

}

}

}

然后 MultipartFile ,MultipartFile是file的抽象,简而言之就是前端上传后端用MultipartFile接受的抽象类

public void uploadMultipartFile ( MultipartFile attachFile) throws IOException {

String path = uploadFileToServer(attachFile.getInputStream(), attachFile.getOriginalFilename(),

"xxxx/xxxxx/" , "");

consultAttach.setAttachName(attachFile.getOriginalFilename());

consultAttach.setAttachSize(attachFile.getSize());

consultAttach.setExtensionName(path.substring(path.lastIndexOf('.')));

consultAttach.setAttachUrl(FileUploadUtil.getFullShowUrl(path));

}

然后是service调用 多文件上传的话传数组MultipartFile[]   单个上传的话 去掉for

public void upload(MultipartFile[] attachFiles) {

if(array == null || array.length == 0){

return;

}

for (MultipartFile attachFile : attachFiles) {

try {

uploadMultipartFile (attachFile);

} catch (IOException e) {

StaticLog.error(e, "上传会诊附件失败");

}

}

}

完成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,可以使用MultipartFile类来实现文件上传功能。以下是一个示例代码,演示了如何将MultipartFile对象转换成File对象并将文件上传服务器: ```java // 定义一个方法,用于将MultipartFile对象转换成File对象 private File transferToFile(MultipartFile multipartFile) { File file = null; try { String originalFilename = multipartFile.getOriginalFilename(); String[] filename = originalFilename.split("."); file=File.createTempFile(filename<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java原生服务器接收上传文件 不使用MultipartFile类](https://download.csdn.net/download/weixin_38640674/12746362)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [使用MultipartFile上传文件服务器MultipartFileFile方法](https://blog.csdn.net/qq_17376623/article/details/109467362)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [java springboot -- MultipartFile -图片上传到远程服务器上](https://blog.csdn.net/weixin_30439067/article/details/96810855)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值