java 图片 header_JAVA 上传图片功能

前后端实现上传图片功能(JAVA代码)

1.前端大概

请求头必须为AJAX请求头: 'X-Requested-With': 'XMLHttpRequest'

一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定文件接收方将以什么形式:

application/x-www-form-urlencoded:数据被编码为名称/值对。这是标准的编码格式。

multipart/form-data: 数据被编码为一条消息,页上的每个控件对应消息中的一个部分。

2.设置请求头格式

Vue.prototype.$sendFormData = axios.create({

baseURL: baseUrl,

timeout: 60000,

headers: {

'X-Requested-With': 'XMLHttpRequest',

'Content-Type': 'multipart/form-data'

},

})

3.AJAX请求代码:

submitUpload() {

// this.$refs.upload.submit();

if(this.imageFileName.length>5){

this.$message('图片不能超过5张');

return false

}

let data  = {};

let files = this.imageFileName;

console.log(files)

let param = new FormData(); //创建form对象

if(files!=''){

files.forEach((n,i)=>{

console.log(n)

n['isFormField']=true;

param.append('broadcastName',n.raw)

// param.append('isFormField',true)

})

param.append('strusercode',this.pubFuc.user.strusercode)

; //单个图片 ,多个用循环 append 添加

console.log(param)

}else{

this.$message.error("图片不对");

return false

}

this.$sendFormData.post('broadcast/uploadPicture',param)

.then(data=>{

if(data.data.result==1000){

this.imageFileName=[];

}else{

this.$message({

type:"error",

message:data.data.msg

})

}

})

},

4.JAVA后台代码(比较长:原因是一个方法,为方便大家看)

@GET

@POST

@Path("/uploadPicture")

@Produces("application/json;charset=UTF-8")

@Consumes("multipart/form-data")

public String uploadPicture(@Context HttpServletRequest request, @Context HttpServletResponse response){

JSONObject resultJson = new JSONObject();

String imgName=null;//给图片定义名称

String imgPath = null;//给图片指定的上传路径

String strusercode=null;

List> list = new ArrayList>();

try{

//创建服务器路径存储图片

imgPath=THESERVERURL+"broadcast\\";

//创建文件夹

File file = new File(imgPath);

if (!file.exists()){// 创建文件夹

file.mkdirs();

}else{

//删除文件中的所有图片

String name[]=file.list();

for (int i=0; i

File f=new File(imgPath,name[i]);//此时就可得到文件夹中的文件

f.delete();//删除文件

}

}

DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置工厂

factory.setRepository(new File(imgPath)); // 设置文件存储位置

factory.setSizeThreshold(1024 * 1024); // 设置大小,如果文件小于设置大小的话,放入内存中,如果大于的话则放入磁盘中,单位是byte

ServletFileUpload upload = new ServletFileUpload(factory);

upload.setHeaderEncoding("utf-8"); // 这里就是中文文件名处理的代码,其实只有一行

List listform = upload.parseRequest(request);

if (listform != null && !listform.isEmpty()){

int sort=0;

for (FileItem fileItem : listform){

sort++;

Map map =new HashMap();

// 判断表单数据是否为普通字段 不是则为图片字段

if (fileItem.isFormField()){

String fieldName = fileItem.getFieldName();// 获取表单字段名称

String value = fileItem.getString("utf-8");// 获取表单字段值

strusercode=value;//获取用户编码

}else{

// 上传图片的保存

String value = fileItem.getName();//值

//String fieldName = fileItem.getFieldName();// 获取表单字段名称

if(value!=null && !"".equals(value)){

// 保存的图片名称  currentTimeMillis时间搓

imgName = System.currentTimeMillis()+ fileItem.getName().substring(fileItem.getName().lastIndexOf("."));

// 保存(写)

fileItem.write(new File(imgPath, imgName));

map.put("broadcastUrl", "broadcast/" + imgName);//图片路径

map.put("booleans", "1");//是否显示图片

map.put("sort", sort);//图片路径

map.put("dtnoticetime", PublicTools.gettime());//上传时间

list.add(map);

}

}

}

//删除表里面的图片记录

userDaoImpl.delete("delete from t_broadcast");

//往表里插入数据

userDaoImpl.insertinto(BroadcastSql.insertSql(list, strusercode));

}else{

return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);

}

} catch (Exception e){

logger.info("登录信息异常",e);

return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);

}

return this.response(resultJson, request);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java 代码实现图片上传下载功能: 1. 图片上传 ``` import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.springframework.web.multipart.MultipartFile; public class ImageUploadUtil { public static void upload(MultipartFile file, String filePath) throws IOException { File dest = new File(filePath); FileUtils.copyInputStreamToFile(file.getInputStream(), dest); } } ``` 使用时,只需要调用 `upload` 方法即可,其中 `file` 是上传的图片文件,`filePath` 是保存到服务器的路径。 2. 图片下载 ``` import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; public class ImageDownloadUtil { public static void download(String filePath, HttpServletResponse response) throws Exception { File file = new File(filePath); if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes())); response.addHeader("Content-Length", "" + file.length()); response.setContentType("application/octet-stream"); FileInputStream fis = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[1024]; int len = 0; while ((len = bis.read(buffer)) > 0) { bos.write(buffer, 0, len); } bos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (fis != null) { fis.close(); } } } } ``` 使用时,只需要调用 `download` 方法即可,其中 `filePath` 是下载图片的路径,`response` 是 HttpServletResponse 对象。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值