当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Can't serve files that are added to my file system after the server is running with Spring-MVC

问题描述:

I'm trying to make a web app where you can upload a file which is saved on my file system and then served to the user at some address (like imgur).

When I upload a file it's saved to the filesystem and it's info into the database. The file is found again and the correct location sent to the appropriate jsp file. However, the jsp file does not display the image, which is the problem. If I restart the server and go to the same address then the jsp displays the file correctly but obviously I can't restart the server every time a file is uploaded just to display it.

This is my UploadController. It just takes files, tags and types from a post request, writes the current file to a location in the file system under a randomly generated name and stores info about the file (type, tags, name and it's location in the filesystem) in a database:

package project.controller;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.util.List;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

import project.service.MediaFile;

import project.service.MediaFileRepository;

@Controller

public class UploadController {

private final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private Random rnd = new Random();

private int randomLength = 8;

@Autowired

private MediaFileRepository repository;

@RequestMapping(value = "/uploadmedia", method = RequestMethod.GET)

public String uploadForm() {

return "upload";

}

@RequestMapping(value = "/uploadmedia", method = RequestMethod.POST)

public String uploadSubmit(@RequestParam(value="files[]") MultipartFile[] files,

@RequestParam("tags[]") String[] tags, @RequestParam("types[]") String[] types)

{

String[] tagsArray;

MultipartFile file;

String name;

String tag;

String path;

String type;

for (int i = 0; i < files.length; i++) {

file = files[i];

tagsArray = tags[i].split("\\s+");

type = types[i];

name = randomString(randomLength);

List<MediaFile> nameExists = repository.findByName(name);

while (nameExists.size() > 0) {

name = randomString(randomLength);

nameExists = repository.findByName(name);

}

path = "/Users/.../src/main/resources/static/img/" + name + type;

if (!file.isEmpty()) {

try {

byte[] bytes = file.getBytes();

BufferedOutputStream stream =

new BufferedOutputStream(new FileOutputStream(new File(path)));

stream.write(bytes);

stream.close();

for (int j = 0; j < tagsArray.length; j++) {

tag = tagsArray[j].toLowerCase();

repository.save(new MediaFile(name, tag, path, type));

}

System.out.println("Success!");

} catch (Exception e) {

System.out.println("Failure... " + e.getMessage());

}

} else {

System.out.println("file is empty");

}

}

return "upload";

}

private String randomString( int len ){

StringBuilder sb = new StringBuilder( len );

for( int i = 0; i < len; i++ )

sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );

return sb.toString();

}

}

...Next, here's my MediaController(The files being uploaded are some sort of media). It just checks if a url has a file with a corresponding name in the database and if it does, sends the path of the file to media.jsp.

package project.controller;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import project.service.MediaFile;

import project.service.MediaFileRepository;

import java.util.List;

/**

* Created by johannesthorkell on 13.10.2015.

*/

@Controller

@RequestMapping("/media")

public class MediaController {

@Autowired

private MediaFileRepository repository;

@RequestMapping("/{media}")

public String newMedia(@PathVariable String media, Model model) {

List<MediaFile> nameExists = repository.findByName(media);

if (nameExists.size() > 0) {

MediaFile mediaFile = nameExists.get(0);

String name = mediaFile.getName();

String type = mediaFile.getType();

model.addAttribute("image", "/img/" + name + type);

return "media";

}

return "error";

}

}

...And finally, here's my media.jsp file. It just takes in the file location from my MediaController and puts it as the src attribute of an img element (the files I'm using to test this are image files).

<!DOCTYPE html>

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Home</title>

</head>

<h1>Media Upload</h1>

<img src="${image}">

<div id="links">

<a href="/uploadmedia">upload media</a>

<a href="/searchmedia">search media</a>

</div>

</body>

</html>

网友答案:

I suspect this is because you're uploading the images into the source tree, not into the location where the application is actually running from (e.g. the target directory). To make it accessible via a url directly, you must store the image in the same directory the web application is running from.

The reason it works after you reload is everything in the source tree is copied to the target directory when you build.

分享给朋友:
您可能感兴趣的文章:
随机阅读: