copy:java实现文件上传功能:https://blog.csdn.net/qq_36725282/article/details/96283347

https://blog.csdn.net/qq_36725282/article/details/96283347

java实现文件上传功能(返回服务器文件路径)

 

 

有时候我们会有一些需求需要上传一些图片或者一些文件,我们写一个小例子来实现这个功能.
我这次是针对上传图片来做的,其实就是后缀名限制,返回自己定义
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/company/public")
public class PublicController {

/**
* 上传用户反馈图片
* @param file
* @param request
* @param response
* @author sunran
* @return
*/
@ResponseBody
@RequestMapping("/upload")
public Object uploadPicture(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request,HttpServletResponse response){
ResultResp result = new ResultResp();
int maxSize = 1024*1024*1; //上传最大为1MB
if (file.getSize()>maxSize) {
result.setMsg("最大上传限制1Mb");
return result;
}
Map<String, Object> map = new HashMap<String, Object>();
File targetFile=null;
String url="";//返回存储路径
String fileName=file.getOriginalFilename();//获取文件名加后缀
if(fileName!=null&&fileName!=""){
String path = "/data/file/";
//String path = "D:/data/file/";
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".image"))) {
result.setMsg("只能上传jpg,jpeg,png,image格式");
return result;
}
//新的文件名
fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
//获取文件夹路径
File file1=new File(path);
//如果文件夹不存在则创建
if(!file1.exists() && !file1.isDirectory()){
file1.mkdirs();
}
//将图片存入文件夹
targetFile = new File(file1, fileName);
try {
//将上传的文件写到服务器上指定的文件。
file.transferTo(targetFile);
//赋予权限
String command = "chmod 775 -R " + targetFile;
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
//生成文件地址
url="http://XXXXXXXXX.cn"+path+"/"+fileName;
result.setCode(200+"");
result.setMsg("图片上传成功");
System.out.println("图片上传成功 url:"+url);
map.put("url", url);
result.setData(map);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("系统异常,图片上传失败");
}
}
return result;
}
————————————————
版权声明:本文为CSDN博主「名字叫孙冉」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_36725282/article/details/96283347

posted @ 2022-02-11 15:37  创嗨  阅读(80)  评论(0编辑  收藏  举报