后台Java代码(Controller)
@RestController
@CrossOrigin
public class FileController {
/*@Resource
FileUploadService fus;*/
// @Resource
// ImageService imageService;
@Value("${file.httpurl}")
private String httpUrl;
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")//yml文件中配置的静态文件本地存储地址D:/tmp/
String uploadFolder;
/**
* 图片上传
* @param imgFile
* @param req
* @return
*/
@PostMapping("upload/file")
public Result<String> upload(@RequestParam("file") MultipartFile imgFile, HttpServletRequest req) {
try {
String oldName = imgFile.getOriginalFilename();
String suffix = oldName.substring(oldName.lastIndexOf("."));
//给文件生成新的唯一的名字
String newName = UUID.randomUUID() + suffix;
String url = "http://localhost:8081/api/image/";
//存在本地文件夹
String path = "D:\\image\\"+newName;
imgFile.transferTo(new File(path));
String imageFileUrl = url+newName;
return Result.success(imageFileUrl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
前端Html代码
(news)
<div class="file" id="file2">
<input type="file" name="pictures" value="上传" id="uploadIn">
<!-- <div class="fileerrorTip2">上传图片</div>-->
<div class="showFileName2"></div>
</div>
js
$('#uploadIn').change(function(e){
console.log(e)
/*
简单的获取选择文件的名字
currentTarget:获取到的是绑定事件的对象
e.currentTarget.files 是一个数组,如果支持多个文件,则需要遍历
*/
var fileMsg = e.currentTarget.files;
var fileTarget = fileMsg[0]
var formData = new FormData();
formData.append("file",fileTarget);
$.ajax({
url: 'http://localhost:8081/upload/file',
type: "post",
data: formData,
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (res) {
console.log(res.data)
$('#releasePicturesId').val(res.data);
},
error: function (error) {
}
});
})
$('.cancel_file_but').click(function(){
$('.inp_file').val(null);
})
(index)
<div class="new_box" style="margin-left: 1%">
<p class="new_time" type="text" id="0n_releaseTime">{{ list.releaseTime}}</p>
<p class="new_title" id="0n_newsTitle" style="text-overflow: ellipsis;voerflow: hidden;white-space: nowrap;">{{ list.newsTitle }}
<a href="#" target="_blank" style="text-decoration: none;" id="0newsTitle" onclick="window.open(list.skipUrl)">{{ list.newsTitle }}</a>
</p>
<div style="width: 90%" id="0n_releasePictures">
</div>
</div>
js
function showData(msg){
var str="";
var p = msg.list;
$.each(p,function (index,item){
for (var i=0;i<10;i++){
var key = i+"n_releasePictures";
var ele = "<img src='"+msg.list[i].releasePictures+"' width='300px' height='100px'/>";
$("#"+key).append(ele);
document.getElementById(i+"n_releaseTime").innerHTML=msg.list[i].releaseTime.substr(0,10);
document.getElementById(i+"n_newsTitle").innerHTML=msg.list[i].newsTitle;
console.log(msg)
}
})
}
数据库存入方式:
后台取出方式